中文词频统计与词云生成

Posted on 2019-03-24 22:13  lawnlawn  阅读(225)  评论(0编辑  收藏  举报

作业要求:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2822

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

  下载的小说为村上春树的《且听风吟》

      

 

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

mytext = open('yuesifengyin.txt',encoding='UTF-8').read()

 

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

      

 

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

jieba.add_word('哈特费尔德')
jieba.add_word('约翰.F.肯尼迪')
jieba.add_word('布鲁克.韦顿')
words = list(jieba.cut(mytext))

 

5. 生成词频统计,排除语法型词汇,代词、冠词、连词等停用词

dele = {'。','!','?','的','“','”','(',')',' ','》','《',','}
wordDict = {}
wordSet = set(words)-dele  ##去除无语义符号

for w in wordSet:    
    if len(w)>1:        
        wordDict[w] = words.count(w)

  

6. 排序

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

  

7. 输出词频最大TOP20

      

 

8.把结果存放到文件里

      

 

9. 生成词云

      

 

10. 完整代码+注释

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
import pandas as pd


text = open('yuesifengyin.txt',encoding='UTF-8').read()


##更新词库,添加词
jieba.add_word('哈特费尔德')
jieba.add_word('约翰.F.肯尼迪')
jieba.add_word('布鲁克.韦顿')
words = list(jieba.cut(text))

##生成词频统计,排除语法型词汇,代词、冠词、连词等停用词
dele = {'','','','','呢','哦','','','','',' ','','',''}
wordDict = {}
wordSet = set(words)-dele
for w in wordSet:
    if len(w)>1:
        wordDict[w] = words.count(w)

##排序
wordlist = sorted(wordDict.items(), key = lambda x:x[1], reverse = True)

cut = " ".join(words)

##生成词云
mywc = WordCloud().generate(cut)
plt.imshow(mywc)
plt.axis("off")
##显示词云
plt.show()

##输出词频最大TOP20
for i in range(20):
    print(wordlist[i])

##把结果存放到文件里
pd.DataFrame(data=wordlist).to_csv('text.csv', encoding='UTF-8')