中文词频统计与词云生成

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

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

下载了《都市愛情故事》

 

二. 从文件读取待分析文本,处理标点符号和格式符。

代码如下:

1
2
3
4
text=open('60380.txt',encoding='utf-8').read()
e='''&# ; ,,.。??!!-::《》< >"“”、\n \r \u3000 \ufeff'''
for i in e:
text=text.replace(i,"")

  

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

安装图:

 

代码如下:

1
2
import jieba
text=jieba.lcut(text);

  

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

 代码如下:

1
2
jieba.load_userdict('ci.txt')
text=jieba.lcut(text);

  

五. 生成词频统计

 代码如下:

1
2
3
4
5
dict={}
for i in tokens:
    if i not in dict:
        dict[i]=tokens.count(i)
print(dict)

  

六. 排序

代码如下:

1
2
word=list(dict.items())
word.sort(key=lambda x: x[1], reverse=True)

  

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

 代码如下:

1
2
# 去除词汇,代词、冠词、连词等停用词
stops=['也','等','的','谁','又','是','新','了','只','一','和','或','区','市','为','在','与','你','我','她'
,'去','人','着','有','来','不','要','好','他','就','说','都','这','把','还','而','到','得'
,'钱','阿','上','会','对','给','这么','一个','对','行','这么','我们','822682268226822682268226','那','很'
,'做','里']
tokens = [token for token in text if token not in stops]

 

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

代码如下:

1
2
3
4
5
result=[]
for i in range(20):
    result.append(word[i])
pd.DataFrame(data=result).to_csv('f.csv',encoding='utf-8')
print(result)

 

文件图: 

 

 

 

九. 生成词云。

词云图:

 

 

十. 总体代码。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import jieba
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件,去除符号
text=open('60380.txt',encoding='utf-8').read()
e='''&# ; ,,.。??!!-::《》< >"“”、\n \r \u3000 \ufeff'''
for i in e:
text=text.replace(i,"")

 
# 加入词库
jieba.load_userdict('ci.txt')
text=jieba.lcut(text);
 
# 去除词汇,代词、冠词、连词等停用词
# 去除词汇,代词、冠词、连词等停用词
stops=['也','等','的','谁','又','是','新','了','只','一','和','或','区','市','为','在','与','你','我','她'
,'去','人','着','有','来','不','要','好','他','就','说','都','这','把','还','而','到','得'
,'钱','阿','上','会','对','给','这么','一个','对','行','这么','我们','822682268226822682268226','那','很'
,'做','里']
tokens = [token for token in text if token not in stops]
 
# 生成词汇统计字典
dict={}
for i in tokens:
    if i not in dict:
        dict[i]=tokens.count(i)
print(dict)
 
# 排序
word=list(dict.items())
word.sort(key=lambda x: x[1], reverse=True)
 
# 输出词频最大TOP20,把结果存放到文件里
result=[]
for i in range(20):
    result.append(word[i])
pd.DataFrame(data=result).to_csv('f.csv',encoding='utf-8')
print(result)
 
# 生成词云
cut_text = " ".join(tokens)
mywc = WordCloud(background_color='black').generate(cut_text)
plt.imshow(mywc)
plt.axis("off")
plt.show()

  

posted on 2019-03-25 17:08  liliguang  阅读(671)  评论(0编辑  收藏  举报