Python词云分析

 import jieba
from matplotlib import pyplot as plt
from wordcloud import WordCloud
from PIL import Image
import numpy as np
txt = (open("红楼梦.txt", "r", encoding='utf-8')).read()
file1 = open("stopwords_cn.txt")
file2 = open("stopwords_cn(more).txt")
ls1 = []
while 1:
line = file1.readline()
new_word = line.strip()
if not line:
break
ls1.append(new_word)
ls2 = []
while 1:
line = file2.readline()
new_word = line.strip()
if not line:
break
ls2.append(new_word)
ls = ls1+ls2
words = jieba.lcut(txt)
counts = {}
for word in words:
for i in ls:
if word == i:
continue
if (len(word)) == 1:
continue
else:
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(15):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
string = ' '.join(words)
print(len(string))
img = Image.open('22.png') #打开图片
img_array = np.array(img) #将图片装换为数组
stopword=['什么', '一个', '我们', '那里', '你们', '如今', '起来', '知道', '这里', '众人', '他们', '出来', '自己', '说道', '听见', '两个', '姑娘', '不好',
'不知', '只见', '东西', '告诉'] #设置停止词,也就是你不想显示的词,这里这个词是我前期处理没处理好,你可以删掉他看看他的作用
stopword=stopword+ls
print(stopword)
wc = WordCloud(
background_color='white',
width=1000,
height=800,
mask=img_array,
font_path='./fonts/simhei.ttf',
stopwords=stopword
)
wc.generate_from_text(string)#绘制图片
plt.imshow(wc)
plt.axis('off')
plt.figure()
plt.show() #显示图片
wc.to_file('new.png') #保存图片

Python词云分析

上一篇:Python——os(二)文件对象


下一篇:洛谷 P4128 [SHOI2006]有色图 解题报告