Python生成词云图:这里引用《勇敢的心》经典台词,进行词云图生成展示。
from wordcloud import WordCloud
# 文本地址
text_path = 'test.txt'
# 示例文本
scr_text = "Fight,and you may die." \
"Run,and you'll live at least a while." \
"And dying in your beds many years from now." \
"Would you be willing to trade?" \
"All the days from this day to that, " \
"for one chance,just one chance, " \
"to come back here and tell our enemies that they may take our lives, " \
"but they'll never take our Freedom!Freedom——"
# 保存示例文本
with open(text_path, 'w', encoding='utf-8') as f:
f.write(scr_text)
# 读取文本
with open(text_path, 'r', encoding='utf-8') as f:
# 这里text是一个字符串
text = f.read()
# 生成词云, WordCloud对输入的文本text进行切词展示。
wordcloud = WordCloud().generate(text)
import matplotlib.pyplot as plt
plt.axis("off")
plt.imshow(wordcloud, interpolation='bilinear')
plt.show()