天天看点

中文统计

中文词频统计

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

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

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

ljieba.lcut(text)

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

jieba.load_userdict("D:\\dict.txt")       

  #词库文本文件

5. 生成词频统计

6. 排序

xu=list(stayed_line.items())
xu.sort(key=lambda x:x[1],reverse=True)      

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

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

xu=list(stayed_line.items())
xu.sort(key=lambda x:x[1],reverse=True)      
import  pandas as pd
pd.DataFrame(data=xu).to_csv("D:\\最强全才.csv",encoding='utf-8')      

9. 生成词云。

具体代码:

# -*- coding: utf-8 -*-
import jieba

#加载停用表
stop = open("D:\\stops.txt", "r",encoding='utf-8').read()
#加载字典文件
jieba.load_userdict("D:\\dict.txt") 

#分解词语
stopwords = []
for word in stop:
    stopwords.append(word.strip())
article = open("D:\\最强全才.txt", "r",encoding='utf-8').read()
words = jieba.cut(article, cut_all = False)
#统计词频
stayed_line = {}
for word in words:
    if word.encode("utf-8") not in stopwords:
        if len(word)==1:
            continue
        else:
            stayed_line[word]=stayed_line.get(word,0)+1

print (stayed_line)

#排序
xu=list(stayed_line.items())
xu.sort(key=lambda x:x[1],reverse=True)

#输出前20个结果
for i in range(20):
    print(xu[i])

#存到csv文件中
import  pandas as pd
pd.DataFrame(data=xu).to_csv("D:\\最强全才.csv",encoding='utf-8')

      
#词云
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wl_split=' '.join(xu)
mywc = WordCloud().generate(words)
plt.imshow(mywc)
plt.axis("off")
plt.show()      

 前20的结果:

中文统计

词云图:

中文统计