第1关 词云练习1
import string
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串,只保留文件中的英文字母和西文符号,过滤掉中
文,所有字符转为小写,将其中所有标点、符号替换为空格,返回英文文本字符串。"""
with open(file, 'r', encoding='utf-8') as f:
res = ''.join([x for x in f.read() if ord(x)<256]).lower()
for c in string.punctuation:
res = res.replace(c, ' ')
return res
def word_frequency(txt):
"""参数 txt去除标点、符号的文本,统计并返回每个单词出现的次数。返回值为字典类型"""
dic = {}
for s in txt.split():
dic[s] = dic.get(s, 0)+1
return dic
def draw_cloud_en_freq(en_frequency):
"""参数 en_frequency为字典类型词频,绘制词云,显示高频单词数量为80个,图片的宽度600,高度400,背景白色、字体最大值150、图片边缘为5,放大画布1.5倍,不随机(random_state=False),不显示坐标轴,词云保存为图片,路径和名为:'result/result.png' """
wc = WordCloud(max_words=80, width=600, height=400,
background_color='White', max_font_size=150,
margin=5, scale=1.5, random_state=False)
wc.generate_from_frequencies(en_frequency)
plt.axis('off')
wc.to_file('result/result.png')
plt.imshow(wc)
if __name__ == '__main__':
filename = 'Who Moved My Cheese.txt' # 英文文件名
content = read_file(filename) # 调用函数返回字典类型的数据
frequency_result = word_frequency(content) # 统计词频
draw_cloud_en_freq(frequency_result) # 调用函数生成词云
plt.show() # 显示图像
第2关 词云练习2
import string
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串,只保留文件中的英文字母和西文符号,过滤掉中
文,所有字符转为小写,将其中所有标点、符号替换为空格,返回英文文本字符串。"""
with open(file, 'r', encoding='utf-8') as f:
res = ''.join([x for x in f.read() if ord(x)<256]).lower()
for c in string.punctuation:
res = res.replace(c, ' ')
return res
def draw_cloud_en_txt(text):
"""参数text读文件获取的文本,绘制词云,显示高频单词数量为80个,
图片的宽度600,高度400,背景白色、字体最大值150、图片边缘为5,
放大画布1.5倍,不随机(random_state=False),不显示坐标轴,
词云保存为图片,路径和名为:'result/result.png' """
wc = WordCloud(max_words=80, width=600, height=400,
background_color='White', max_font_size=150,
margin=5, scale=1.5, random_state=False)
wc.generate(text)
plt.axis('off')
wc.to_file('result/result.png')
plt.imshow(wc)
if __name__ == '__main__':
filename = 'Who Moved My Cheese.txt' # 英文文件名
content = read_file(filename) # 调用函数返回字典类型的数据
draw_cloud_en_txt(content)
第3关 词云练习3
import jieba.analyse
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def read_file(file):
"""接收文件名为参数,将文件中的内容读为字符串"""
with open(file, 'r', encoding='utf-8') as f:
return f.read()
def word_frequency_cn(txt):
"""参数 txt读文件获取的文本,jieba.analyse.textrank()可用参数topK设置最多返回多少个按词频降序排列的关键词列表,
数据格式为列表:[('人民', 1.0), ('中国', 0.9533997295396189), ...],
将列表转为字典:{'人民': 1.0, '中国': 0.9533997295396189,...},返回这个字典"""
List = jieba.analyse.textrank(txt, topK=60, withWeight=True)
print(List)
return dict(List)
def draw_cloud_cn(frequency_dict):
"""参数为词频,字典类型,设定图片的中文字体为('fonts/MSYH.TTC')、背景为白色、
背景图片'ball.jpg'、字体最大值200、按比例进行放大画布2倍,储存为 result/result.png"""
bg = plt.imread('ball.jpg')
wc=WordCloud(font_path='fonts/MSYH.TTC',
background_color='White',
mask=bg, max_font_size=200,
scale=2, random_state=False)
wc.generate_from_frequencies(frequency_dict)
plt.axis('off')
wc.to_file('result/result.png')
plt.imshow(wc)
if __name__ == '__main__':
filename = '湿地公约.txt' # 用于生成词云的中文文件名
content = read_file(filename)
frequency = word_frequency_cn(content) # 利用jieba对文本进行分词,并统计词频
draw_cloud_cn(frequency) # 绘制词云
如果此文章对你有所帮助,麻烦点个赞,谢谢~~~
点赞加关注,追新不迷路~~~