代码改变世界

中文词频统计

2019-03-18 19:44  科ke  阅读(212)  评论(0编辑  收藏  举报

中文词频统计

1. 下载一长篇中文小说。

2. 从文件读取待分析文本。

3. 安装并使用jieba进行中文分词。

pip install jieba

import jieba

ljieba.lcut(text)

4. 更新词库,加入所分析对象的专业词汇。

jieba.add_word('天罡北斗阵')  #逐个添加

jieba.load_userdict(word_dict)  #词库文本文件

5. 生成词频统计

6. 排序

7. 排除语法型词汇,代词、冠词、连词

8. 输出词频最大TOP20,把结果存放到文件里

9. 生成词云。

import jieba


article = open('test.txt','r',encoding='utf-8').read()

jieba.add_word('北灵院')

words = list(jieba.lcut(article))
dictory = {}
dele = {'\n',' ','','','','','?','','',','
        ,'','','','','','','','',''
        ,'','','','','','','','',''
        ,'','','','',''}

set = set(words)-dele

for w in set:
        dictory[w] = words.count(w)

word = sorted(dictory.items(),key = lambda x:x[1], reverse = True)

for i in range(20):
    print(word[i])

from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image,ImageSequence
import numpy as np


image= Image.open('timg.jpg')
graph = np.array(image)
cut_text = " ".join(words)
font=r'C:\\Windows\\Fonts\\STFANGSO.ttf'
wordcloud = WordCloud(font_path=font,background_color='White',max_words=50,mask=graph).generate(cut_text)

plt.imshow(wordcloud)
plt.axis("off")
plt.show()