|
我想有一个程序把一篇中文文章或书籍的字列出来。每个字的使用次数。每次使用所在的句子。然后按照拼音顺序排序输出到一个文件里。
目前统计字频部分已经写好了。如下:
# -*- encoding: gbk -*-
def is_chinese(uchar):
"""判断一个unicode是否是汉字"""
if uchar >= u'\u4E00' and uchar <= u'\u9FA5':
return True
else:
return False
def count_chinese_word(filepath, encoding):
_dict = {}
try:
with open (filepath, 'r') as txt_file:
for line in txt_file:
ustr = line.decode(encoding)
for uchar in ustr:
if is_chinese(uchar):
if _dict.has_key(uchar):
_dict[uchar] = _dict[uchar] + 1
else:
_dict[uchar] = 1
except IOError as ioerr:
print "文件",filepath,"不存在"
return _dict
if __name__ == '__main__':
_dict = count_chinese_word('内容.txt', 'gbk')
import json
print json.dumps(_dict, encoding = "utf-8", indent = 4, ensure_ascii = False)
但是我不太会如何输出每个字每次使用所在的句子,求教吧里各位大神。万分感谢
|
|