Python生成词云

前言

最近了解到python 可以做词云,那么下面来玩玩看。
分析一下红楼梦出现的人物名,并生成自定义图案的词云

1.准备工作

安装需要用到的第三方库

  • jieba
  • matplotlib
  • wordcloud
  • imageio

    2.思路

    首先先分析清洗数据,提取关键词,然后生成词云

    3.代码实现

    3.1 准备的文件

    首先需要有这个红楼梦.txt 、star.jpg、stop_words.txt等文件,文章最下面已经给出了获取的链接

3.2 代码如下:

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
43
44
45
46
import jieba

# 获取文本
def getText(filePath):
file = open(filePath,'r',encoding='utf-8')
text = file.read()
file.close()
return text

# 提取关键词
def wordFreq(filePath,text,topn):
words = jieba.lcut(text.strip())
counts={}
stopwords = stopwordslist('./stop_words.txt')
for word in words:
if len(word) == 1:
continue
elif word not in stopwords:
if word == "凤儿姐":
word="凤姐"
elif word == "林黛玉" or word=="林妹妹" or word=="黛玉笑":
word="黛玉"
elif word=="宝二爷":
word="宝玉"
elif word=="裘人道":
word="裘人"
else:
counts[word] = counts.get(word,0)+1
items = list(counts.items())
items.sort(key= lambda x:x[1], reverse=True)
f = open(filePath[:-4]+'_词频.txt','w')
for i in range(topn):
word, count = items[i]
f.writelines("{}\t{}\n".format(word,count))
f.close()

# 过滤一些词
def stopwordslist(filePath):
stopwords = [line.strip() for line in open(filePath,'r',encoding='utf-8').readlines()]
return stopwords

filePath="./红楼梦.txt"
text = getText(filePath)
print(text)
print(filePath)
wordFreq(filePath,text,30)

执行代码后,得到一个红楼梦_词频.txt文件。

那么接下来就是生成词云图片

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

import matplotlib.pyplot as plt
import wordcloud
# from scipy.misc import imread
from imageio import imread

bg_pic=imread('./star.jpg')
f = open("./红楼梦_词频.txt",'r')
text = f.read()
f.close()
dictText= []
temp=[]
count = 0
for i in range(len(text)):
if text[i] == '\n':
temp = text[:i].split()
dictText.append((temp[count],float(temp[count+1])))
count += 2

wcloud = wordcloud.WordCloud(
background_color="white",
width=1000,
height=860,
max_words=50,
margin=1,
font_path='C:\Windows\Fonts\STXINGKA.ttf',
mask = bg_pic,

).fit_words(dict(dictText))
plt.imshow(wcloud)
plt.axis('off')
plt.show()

执行之后得到这样子的效果:
image.png

代码资料链接如下:
https://github.com/silin528/python/tree/main/%E8%AF%8D%E4%BA%91

查看评论