因为工作需要,写一个python脚本,检索文件中的所有汉字,遇到了一点坑
检索一类特征的东西当然需要用正则表达式了,python中的re
先看原始代码,python版本2.7
#!/sr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import re
def searchword(path):
f = open(path)
lines = f.readlines()
pattern = re.compile(u"[\u4e00-\u9fa5]+")
for line in lines:
line.decode('utf8')
results = re.findall(pattern, line)
for str in results:
print str
f.close()
按照网上的林林总总,这样写看着没有什么问题,但是测试通不过,检索不出汉字
为什么呢?
先是想编码问题,可是已经
line.decode('utf8') utf8编码了呀,应该没问题才对,为了测试,加了一句代码
line.decode('utf8')
print isinstance(line, unicode)
结果为False, 所以显然字符串编码非unicode,具体原因还未知,python也是即用即查的,后续认真探索一下
line.decode('utf8') -----> line = unicode(line, 'utf-8')代码替换城这个,发现编码为unicode了,检索也好使了,暂且记录一下,原因待查
line.decode('utf8')