以词的大小显示出词出现的次数的占比
一、 词云模块
1. 下载:pip install wordcloud
2. 导入:from wordcloud import WordCloud
3. 简单代码示例
# 词云:以词的大小显示词出现的次数
from wordcloud import WordCloud
import jieba
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
# 读文件
texts = []
with open('../data_ML/棋王.txt', encoding='utf-8') as f:
for sw in f.readlines():
texts.append(sw.strip('\n').strip().replace(' ', ''))
texts = str(texts)
# 分词后,再次转换为字符串
texts = ' '.join(list(jieba.cut(texts, cut_all=False)))
print(texts)
# 处理图片文件,将其转换为数组形式
# 读图像
img = Image.open('../data_ML/qie.png')
# 将图像转换为数组
img = np.array(img)
# print(img.shape) # (436, 799, 4)
# 词云操作
# 实例化词云对象
wc = WordCloud(
font_path='simhei.ttf', # 字体路径,中文存在乱码,需要加入字体
width=500, # 宽度
height=250, # 高度
background_color='white', # 背景颜色
random_state=1, # 随机种子
mask=img, # 图像,需要为数组的形式,填充非白色区域
collocations=False, # 设置该参数,可以去除重复字
# max_words=20 # 词云最多显示词
)
# 词云对象:生成text文本
wc.generate_from_text(texts)
# imshow放入内容,但不直接显示
plt.imshow(wc)
# 关闭坐标轴
plt.axis('off')
# 保存图片
plt.savefig('词云显示.png')
# 直接显示
plt.show()
结果展示
二、pyecharts下的词云
可以参考pyecharts官网
from pyecharts import options as opts
from pyecharts.charts import WordCloud
import jieba
from collections import Counter
'''
with open('../data_ML/resource/ham_5000.utf8', encoding='utf-8') as f:
ham_text = f.readlines()
# 结果为一个列表,每行分词结果被作为一个元素
feature = []
for tmp in ham_text:
out = list(jieba.cut(tmp, cut_all=False))
# print(out)
feature.extend(out)
# print(feature)
feature = ' '.join(feature)
print('分词后:\n', type(feature))
# Counter:对字符串/列表/元组/字典进行计数,返回一个字典类型的数据
# ---------键是元素,值是元素出现的次数
# most_common(50):统计出现做多次数的50个元素
out = Counter(feature).most_common(50)
print(out)
'''
out = [(' ', 672023), (',', 35254), ('的', 27890), ('是', 15996), ('我', 15552), ('不', 14424),
('。', 13556), ('了', 12114), ('一', 12108), ('有', 9018), ('人', 7969), ('个', 7811),
('.', 7763), (':', 6937), ('在', 6684), ('他', 6038), ('这', 5912), ('你', 5786),
('e', 5698), ('就', 5645), (',', 5379), ('\n', 5000), ('说', 4851), ('好', 4789),
('么', 4704), ('要', 4504), ('来', 4471), ('很', 4352), ('没', 4262), ('也', 4163),
('大', 4097), ('-', 4032), ('上', 3925), ('时', 3863), ('a', 3824), ('0', 3820),
('~', 3758), ('都', 3586), ('还', 3570), ('到', 3542), ('以', 3530), ('?', 3498),
('得', 3479), ('她', 3462), ('可', 3456), ('生', 3372), ('看', 3278), ('m', 3248), ('自', 3239), ('i', 3236)]
c = (WordCloud()
.add('', out, word_size_range=[12, 55],
mask_image='../data_ML/qie.png',
shape='cardioid')
.set_global_opts(title_opts=opts.TitleOpts(title="WordCloud-自定义图片"))
.render("wordcloud_custom_mask_image.html")
)
结果展示
三、计数Counter
Counter:对字符串/列表/元组/字典进行计数,返回一个字典类型的数据,键是元素,值是元素出现的次数; most_common(50):统计出现做多次数的50个元素
- 导包:
from collections import Counter
- 函数:
Counter()
- 简单示例:
from collections import Counter
text = 'hello, this is pangpang. i love study, fighting'
out = Counter(text).most_common(5)
print(out)
结果展示