中文词频统计

中文词频统计

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

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

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

pip install jieba

import jieba

ljieba.lcut(text)

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

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

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

参考词库下载地址:https://pinyin.sogou.com/dict/

转换代码:scel_to_text

  1. 生成词频统计

  2. 排序

  3. 排除语法型词汇,代词、冠词、连词等停用词。

stops

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

  2. 生成词云。

安装词云:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple wordcloud

下载安装:下载 https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud

安装 找到下载文件的路径 pip install wordcloud-1.5.0-cp37-cp37m-win_amd64.whl

配置:

在WordCloud安装的目录下找到WordCloud.py文件,对源码进行修改。

编辑wordcloud.py,找到FONT_PATH,将DroidSansMono.ttf修改成msyh.ttf。这个msyh.ttf表示微软雅黑中文字体。

在同一个目录下放置msyh.ttf字体文件供程序调用(字体可以在C:\Windows\Fonts复制)

使用:

1、引入模块

from wordcloud import WordCloud

import matplotlib.pyplot as plt

2、导入文本

准备生成词云的文本word_text =' '.join(wordlist) #是以空格分隔的字符串

4、生成词云

mywc = WordCloud().generate(wl_split)

5、显示词云

plt.imshow(mywc)

plt.axis("off")

plt.show()

源代码如下:
import jieba
txt=open('meng.txt','r',encoding='utf-8').read()

stopwords = [line.strip() for line in open('stops_chinese1.txt',encoding='utf-8').readlines()]

wordsls=jieba.lcut(txt)
wcdict={}
for word in wordsls:
if word not in stopwords:
if len(word)==1:
continue
else:
wcdict[word]=wcdict.get(word,0)+1
jieba.add_word('蒙先生')
jieba.add_word('黄女士')

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

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

from wordcloud import WordCloud
import matplotlib.pyplot as plt
wails=list(wcdict.items())
wails.sort(key=lambda x:x[1], reverse=True)

cut_text = " ".join(wordsls)
'print(cut_text)'
mywc = WordCloud(font_path = 'msyh.ttc').generate(cut_text)
plt.imshow(mywc)
plt.axis("off")
plt.show()

词云图:

运行截图:

posted on 2019-03-18 21:57  大大大大猫呀  阅读(200)  评论(0编辑  收藏  举报

导航