parent
9b0894c748
commit
d4c64867d4
@ -1,45 +1,45 @@
|
|||||||
import jieba
|
import jieba
|
||||||
from matplotlib import pyplot as plt
|
from matplotlib import pyplot as plt
|
||||||
from wordcloud import WordCloud
|
from wordcloud import WordCloud
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
def predeal(txt):
|
def predeal(txt):
|
||||||
cut = jieba.cut(txt) # 分词
|
cut = jieba.cut(txt) # 分词
|
||||||
string = ' '.join(cut)
|
string = ' '.join(cut)
|
||||||
return string
|
return string
|
||||||
|
|
||||||
def drawcloud(imgpath, stopword, string, savepath):
|
def drawcloud(imgpath, stopword, string, savepath):
|
||||||
try:
|
try:
|
||||||
img = Image.open(imgpath) # 打开图片
|
img = Image.open(imgpath) # 打开图片
|
||||||
except IOError as e:
|
except IOError as e:
|
||||||
print(f"打开图片时出错:{e}")
|
print(f"打开图片时出错:{e}")
|
||||||
return
|
return
|
||||||
img_array = np.array(img) # 将图片转换为数组
|
img_array = np.array(img) # 将图片转换为数组
|
||||||
wordcloud = WordCloud(
|
wordcloud = WordCloud(
|
||||||
background_color='white',
|
background_color='white',
|
||||||
width=1000,
|
width=1000,
|
||||||
height=800,
|
height=800,
|
||||||
mask=img_array, # 设置背景图片
|
mask=img_array, # 设置背景图片
|
||||||
font_path='C:\\Windows\\Fonts\\msyh.ttc', # 电脑自带的字体
|
font_path='C:\\Windows\\Fonts\\msyh.ttc', # 电脑自带的字体
|
||||||
stopwords=stopword,
|
stopwords=stopword,
|
||||||
colormap='plasma'
|
colormap='plasma'
|
||||||
)
|
)
|
||||||
wordcloud.generate_from_text(string) # 绘制图片
|
wordcloud.generate_from_text(string) # 绘制图片
|
||||||
plt.imshow(wordcloud)
|
plt.imshow(wordcloud)
|
||||||
plt.axis('off')
|
plt.axis('off')
|
||||||
wordcloud.to_file(savepath) # 保存图片
|
wordcloud.to_file(savepath) # 保存图片
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
txtpath = r'd:\学习\软件工程\swork\res\select_ai.txt'
|
txtpath = r'd:\学习\软件工程\swork\res\select_ai.txt'
|
||||||
imgpath = r'd:\学习\软件工程\swork\tu4.png'
|
imgpath = r'd:\学习\软件工程\swork\tu4.png'
|
||||||
savepath = r'd:\学习\软件工程\swork\cloud_ai.png'
|
savepath = r'd:\学习\软件工程\swork\cloud_ai.png'
|
||||||
stopword = ['啊', '的', '是', '视频', '个', '哈', '第', '哈哈哈', '吧', '了', '我', '你'] # 设置不想显示的词
|
stopword = ['啊', '的', '是', '视频', '个', '哈', '第', '哈哈哈', '吧', '了', '我', '你','福州大学'] # 不想显示的词
|
||||||
try:
|
try:
|
||||||
with open(txtpath, 'r', encoding='utf-8') as file:
|
with open(txtpath, 'r', encoding='utf-8') as file:
|
||||||
txt = file.read()
|
txt = file.read()
|
||||||
except FileNotFoundError as e:
|
except FileNotFoundError as e:
|
||||||
print(f"读取文本文件时出错:{e}")
|
print(f"读取文本文件时出错:{e}")
|
||||||
else:
|
else:
|
||||||
string = predeal(txt)
|
string = predeal(txt)
|
||||||
drawcloud(imgpath, stopword, string, savepath)
|
drawcloud(imgpath, stopword, string, savepath)
|
Loading…
Reference in new issue