`

python的一些记录

 
阅读更多

正则表达式的一些常用元字符和语法: http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

 

正则表达式匹配html问题,经常会出现正则写对了,但匹配就是不成功,用notepad++查看html代码。

原因是:查看的html代码中,各html标签间可能有换行符,tab符等不可见字符,所以要在各html间增加【\s*】来匹配,同时python的使用中也要打开re.S 来 dot match all(包括换行)

for each in re.findall(person,page,re.S):
	print each

 

对于utf-8编码的网页,用urllib2下载网页时,正确处理中文的方法是:decode('utf-8)

page = urllib2.urlopen(url).read().decode('utf-8')

 

中文写到文件的方法:(在windows下,文件默认是ansii编码)

file = open(r'e:\\Chow\\result.txt','w')
...
print >>file,each.encode('gbk'),'\n'

 或者用codecs模块,以utf-8打开文件:

file = codecs.open(r'e:\\Chow\\result.txt','w','utf-8')
...
print >>file,each,'\n'

 

 

1.写文件中文问题

在windows写中文txt文件时,遇到问题:

 

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 0: ordinal
not in range(128)

解决:

 

 

import codecs

file = codecs.open('filepath', 'w', 'utf-8')
str = '中文输入'
file.write(str.decode('gbk'))
fiile.close()

或者:

在python的安装目录下的Lib目录,找到site.py,修改def setencoding()方法
def setencoding():
   .....
   ....
    if 0:
        # Enable to support locale aware default string encodings.

把那个if 0改为if 1: 

 

 

 

 

.py文件的第一行加入:

#-*- encoding:UTF-8 -*-

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics