本帖最后由 孤独的嫖客 于 2021-2-23 12:54 编辑
先上图:
申明:采用图像仅用作美化词云展示效果,评论内容与图像无关!
更新2021年2月23日- 修改了目录结构,使其看起来更加清晰明了
- 取消了jieba分词,让词云还原评论本质
- 尝试使用pyecharts作图(TODO)未完成
功能实现:
- 获取程序运行路径,方便服务器部署
- pandas 读取csv指定列保存到txt
- 使用中文分词 jieba 对评论做语言处理
- 使用停用词排除干扰
- 使用 Worldcloud 创建词云
- 使用自定义画像美化词云
注意:worldcloud 使用pip install 无法直接安装成功(macos,linux 未测试) 安装worldcloud 需要whl文件,imgs文件夹中附带了适配win10 64位 python3.9版本的whl文件,相同环境可以直接使用 pip install 绝对路径+wordcloud-1.8.1-cp39-cp39-win_amd64.whl安装 其他python版本的可以到这里下载whl文件 - https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud
复制代码最后建议脚本运行环境为python 3.8以上 因为脚本使用了3.8版本的新特性 代码展示:- from wordcloud import WordCloud
- from imageio import imread
- import pandas as pd
- import os
- import logging as log
- # 设置停用词
- stopword = ['什么', '没有', '真的', '这种', '那里',
- '就是', '可以', '一个', '还是', '最后',
- '这个', '但是', '总之', '不要', '这部',
- '一部', '故事', '这么', '出来', '应该',
- '电影', '不是', '为了', '还有', '你们',
- '系列', '觉得', '自己', '已经', '整个',
- '一直', '还是', '出来', '完全', '看到'
- '那个', '之后', '除了', '其中', '长泽雅美',
- '陈思诚', '妻夫木聪', '浅野忠信', '铃木保奈美',
- 'the','world','大过年的','三浦友和']
- # def fenci():
- # # 设置用户字典
- # jieba.load_userdict(parent_dir+"\\imgs\\自定义字典.txt")
- # with open(filepath, "r", encoding="utf8") as f:
- # file = f.read()
- #
- # # 数据清洗
- # wordslist = jieba.lcut(file)
- # with open(parent_dir + "\\tmp\\分词结果.txt", "w", encoding="utf8") as f:
- # f.write(" ".join(wordslist))
- # log.info("数据分词完毕,开始清洗...")
- # regworld = list()
- # for i in wordslist:
- # if len(i) > 1:
- # regworld.append(i)
- #
- #
- # outworld = list()
- # for i in regworld:
- # if i not in stopword:
- # outworld.append(i)
- # with open(parent_dir+"\\tmp\\清洗结果.txt", "w", encoding="utf8") as f:
- # f.write(" ".join(outworld))
- # words = " ".join(outworld)
- # return words
- def creatCiYun(words):
- log.info("数据清洗完毕,开始画图...")
- fontpath = parent_dir + "\\imgs\\Alibaba-PuHuiTi-Regular.ttf"
- bgpic = imread(parent_dir + "\\imgs\\3.png")
- wc = WordCloud(font_path=fontpath,stopwords=stopword,
- mask=bgpic,scale=3,
- background_color='white', )
- wc = wc.generate(words)
- wc.to_file(parent_dir + "\\tmp\\唐探3.png")
- if __name__ == '__main__':
- # 日志初始化
- log.basicConfig(level=log.INFO, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
- # 获取相对路径
- parent_dir = os.path.dirname(os.path.abspath(__file__))
- log.debug(f"程序运行路径{parent_dir}")
- filepath = parent_dir + "\\tmp\\tempdata.txt"
- # 判断程序是否首次运行,是则读取csv,非首次运行不需要读取csv
- try:
- f = open(filepath, "r")
- f.close()
- except IOError:
- log.info("初始化中....")
- f = open(filepath, "w", encoding="utf8")
- f.close()
- # 读取评论
- df = pd.read_csv(parent_dir + '\\imgs\\Ori.csv', usecols=[3])
- # 提取所有评论写入txt,为分词做准备工作
- df.to_csv(filepath, sep="\t", index=False, header=None)
- # data = fenci()
- with open(parent_dir+"\\tmp\\tempdata.txt","r",encoding="utf8") as f:
- data = f.read()
- creatCiYun(data)
复制代码
补充一下项目地址,不然没有图像,字体资源,程序无法直接运行- https://gitee.com/Rt_hum/three-words-of-tang-tan
复制代码
感谢论坛的活动,学习了词云可视化
|