Home >Backend Development >Python Tutorial >python用字典统计单词或汉字词个数示例

python用字典统计单词或汉字词个数示例

WBOY
WBOYOriginal
2016-06-16 08:44:251506browse

有如下格式的文本文件

复制代码 代码如下:

/“/请/!/”/“/请/!/”/两名/剑士/各自/倒转/剑尖/,/右手/握/剑柄/,
/左手/搭于/右手/手背/,/躬身行礼/。/两/人/身子/尚未/站/直/,
/突然/间/白光闪/动/,/跟着/铮的/一/声响/,
/双剑相/交/,/两/人/各/退一步/。
/旁/观众/人/都/是/“/咦/”/的/一声/轻呼/。/青衣/剑士/连/劈/三/剑/

将这段话进行词频统计,结果是  词—词数  的形式,比如  请  2  ,并把结果放到txt文件中。

这样的问题利用词或单词作为字典的key,循环判断有不有这个key,没有新增一个,有的话,将这个key对应的value加1

复制代码 代码如下:

#coding:utf-8
word_lst = []
word_dict = {}

with open("中文.txt","r") as f1 ,open("词次数.txt",'w') as f2:
   for line in f1:
       word_lst.append(line.split('/'))

   for item in word_lst:
       for item2 in item:
           if item2.strip() not in ",!。“”" :
               if   item2 not in word_dict:
                   word_dict[item2] = 1
               else :
                   word_dict[item2] += 1

   for key in word_dict:
       print key,word_dict[key]
       f2.write(key+' '+str(word_dict[key]))

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn