from wordcloud import WordCloud import matplotlib.pyplot as plt # 读取弹幕文件 with open("弹幕.txt", "r", encoding="utf-8") as file: all_danmaku = file.readlines() # 去除空白字符,并合并成一个长字符串 danmaku_text = ''.join(all_danmaku).replace('\n', '') # 使用WordCloud生成词云图 def generate_wordcloud(text): # 指定中文字体路径 font_path = 'C:\\Windows\\Fonts\\msyh.ttc' # 微软雅黑字体路径 # 创建词云对象 wordcloud = WordCloud( font_path=font_path, # 设置字体路径 width=800, height=400, background_color='white' # 设置背景颜色 ).generate(text) # 显示词云图 plt.figure(figsize=(10, 5)) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') # 不显示坐标轴 plt.show() # 保存词云图到文件 wordcloud.to_file("danmaku_wordcloud.png") # 调用函数生成词云图 generate_wordcloud(danmaku_text)