python词云图到词云视频完整教程
【Python-人物词云视频分解教程】-002-静态多彩词云图制作,简单易用,自由度高,代码地址在视频中
本文档图片和文本素材:
链接:https://pan.baidu.com/s/1xLO1XsNd6mY7uBOjjwobxg
提取码:lang
词云图结果对比展示
代码介绍
基本代码和常用参数介绍
# 一般需要安装的库有 wordcloud jieba matplotlib
# 所用模块 按需导入就可以 所用功能 也按需使用
from wordcloud import WordCloud # 绘制词云的模块,注意大小写
from wordcloud import ImageColorGenerator # 自动控制词云颜色的模块,有需要再引入
import jieba # 结巴分词库 用于将长段的文本句子 切成 词语
import matplotlib.pyplot as plt # matplotlib的pyplot来控制和绘图相关的功能
import matplotlib.image as mping # matplotlib的mping来生成蒙版图片
from matplotlib import colors # matplotlib的颜色模块 用来指定组成词云单词的字体颜色
import jieba.analyse # 用于让结巴库 自己提取文本的关键词 降低无关词汇对词云的干扰(关键词:重要性权重比较高的词)
# 准本字符串文本内容 一般会是从文件中读取的
txt_ori = """
《爱丽丝梦游仙境》(又名爱丽丝漫游奇境;英语:Alice's Adventures in Wonderland)是英国作家查尔斯·路德维希·道奇森以笔名路易斯·卡罗尔于1865年出版的儿童文学作品。故事叙述一个名叫爱丽丝的女孩从兔子洞进入一处神奇国度,遇到许多会讲话的生物以及像人一般活动的纸牌,最后发现原来是一场梦。本书出版之后即广受欢迎,儿童和成人都喜爱这部作品,并且反复再版至今。至今已有超过五十种语言的译本,上百种不同版本,以及许多戏剧、电影等改编作品。在英文中,本书通常被简称为Alice in Wonderland,并适用于大部分的改编作品。
"""
# 设置指定形状词云的方法
# 如果想生成指定形状的词云 需要先传入一张控制形状的蒙版图片 不要传入透明图片。
# 透明区域可以改成白色,图片白色区域将不会绘制词云。 注意下面那个 *255 记得加上。
# 记得在下面WordCloud对象参数mask后传入即可 mask=img_mask
img_mask = mping.imread('爱丽丝黑白.png')*255
# 如果想指定颜色可以这么设置
# 建立颜色数组,可指定组成词云的字体颜色
# 不清楚颜色值选什么的 可以去这个颜色对照网站自己复制 https://tool.oschina.net/commons?type=3
color_list=['#1ed1f6','#1431ff','#1484ff','#ff145e']
# 调用 然后在下面WordCloud对象参数colormap后传入即可 colormap=colormap
colormap=colors.ListedColormap(color_list)
# 手动设置停用词 stopwords格式是一个集合 stopwords = {'的','地','说'.....'于是'} 可以直接使用集合去设置
# 然后在下面WordCloud对象参数stopwords后传入即可 stopwords=stopwords
stopwords = {'你', '呢', '又', '人', '但是', '把', '那', '就', '地', '上下', '他', '我', '吧', '会',
'一', '们', '着', '哦', '去', '什么', '了', '那么', '在', '它', '是', '这', '可是', '都',
'啊', '没', '这样', '于是', '她', '说', '不', '也', '这时', '的', '哪个', '有', '一个', '嗯', '没有','得'}
# 也可以像下面一样用结巴分词后再转成集合
# stopwords_txt = '的地说了是我他你她它着没呢在吧也啊嗯哦就这那哪个人但是有又们一这样没有都把去上下会一个什么不于是'
# stopwords_list = jieba.lcut(stopwords_txt)
# stopwords = set(stopwords_list)
# 利用 ImageColorGenerator 函数将词云颜色设置为根据图片颜色确定
# 调用 然后在下面WordCloud对象参数color_func后传入即可 color_func = image_colors
image_colors = ImageColorGenerator(img_mask)
# 创建词云对象参数介绍
w = WordCloud(width=640, # 设置词云宽度为640像素
height=480, # 设置词云高度为480像素
background_color='white', # 设置词云图的背景色
font_path='simhei', # 设置词云的字体
mask=None, # 设置词云蒙版 没有设置默认等于None
stopwords=None, # 设置停用词 是一个集合 没有设置默认等于None
contour_color='gray', # 设置词云边框颜色
contour_width=1, # 设置词云边框宽度 0是没有边框 一般用在指定形状的词云设置中
colormap=None, # 设置组成词云的字体的颜色
color_func = None, # 设置根据某种模式设置组成词云的字体颜色 比如根据图片的颜色对应设置词云颜色
max_words = 200, # 设置最多显示多少个词 默认是200
max_font_size=80, # 设置最大的字体字号
min_font_size=2, # 设置最小的字体字号
scale=1 # 缩放比例 一般 1~4 即可 避免分辨率不够导致有些字太小看不清
)
# 生成词云 默认是以传入文本的方式生成词云
w.generate(txt_ori)
# 保存词云成图片 传入自定义的名字和后缀名即可
w.to_file('词云图.png')
# 设置展示图片的画布的大小 和 分辨率 可以自由调整
plt.figure(figsize=(10, 4),dpi=300)
# 加载要展示的图片 w 是上面的词云对象
plt.imshow(w)
# 显示加载的图片
plt.show()
简单词云
from wordcloud import WordCloud
import matplotlib.pyplot as plt
txt_ori = """
《爱丽丝梦游仙境》(又名爱丽丝漫游奇境;英语:Alice's Adventures in Wonderland)是英国作家查尔斯·路德维希·道奇森以笔名路易斯·卡罗尔于1865年出版的儿童文学作品。故事叙述一个名叫爱丽丝的女孩从兔子洞进入一处神奇国度,遇到许多会讲话的生物以及像人一般活动的纸牌,最后发现原来是一场梦。本书出版之后即广受欢迎,儿童和成人都喜爱这部作品,并且反复再版至今。至今已有超过五十种语言的译本,上百种不同版本,以及许多戏剧、电影等改编作品。在英文中,本书通常被简称为Alice in Wonderland,并适用于大部分的改编作品。
"""
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=None,colormap=None,
stopwords=None,contour_color='gray',contour_width=1,
max_words = 200,max_font_size=80, min_font_size=2,scale=1
)
# 默认是以传入文本的方式生成词云
w.generate(txt_ori)
w.to_file('简单词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
指定形状词云
现在还没设置分词 运行结果 可以观察到词云的构成 多是以句子为主
黑白底片蒙版图
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
# 记得把img_mask 传给下面WordCloud的参数mask
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=None,contour_color='gray',contour_width=0,
max_words = 200,max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_ori)
w.to_file('指定形状词云黑白底片图.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
彩色蒙版图
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
# 记得把img_mask 传给下面WordCloud的参数mask
# img_mask = mping.imread('爱丽丝黑白.png')*255
img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=None,contour_color='gray',contour_width=0,
max_words = 200,max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_ori)
w.to_file('指定形状词云彩色蒙版图.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
指定形状结巴分词词云
结巴库的常规使用
import jieba
txt = "我是一个成熟的分词库了,我分词很强大"
txt_cut = jieba.lcut(txt)
print(txt_cut)
# 分割完后是一个列表,我们再 用空格 把列表拼接成字符串格式 将来词云会根据空格来取我们的词
txt_str = " ".join(txt_cut)
print(txt_str)
['我', '是', '一个', '成熟', '的', '分', '词库', '了', ',', '我', '分词', '很', '强大']
我 是 一个 成熟 的 分 词库 了 , 我 分词 很 强大
结巴分词绘制词云
运行结果 可以观察到词云的构成 多是以词语,单字为主 但是还是会有很多无用的词 什么 的 地 得 等等
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
# 使用结巴库对文本内容进行分割
txt_cut = jieba.lcut(txt_ori)
# 分割完后是一个列表,我们再 用空格 把列表拼接成字符串格式 词云会根据空格来取我们的词
txt_str = " ".join(txt_cut)
font = "simhei"
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=None,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('指定形状结巴分词词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
指定形状 和 停用词 词云
停用词:也就是停用掉无关的词。减少无关词汇对词云观赏度的影响。 比如 的 地 得 啊 嗯 等等。
设置:
方法一:
我们可以自己手动设置中文停用词。
方法二:
也可以利用wordcloud 自带的停用词工具模块自动设置英文的停用词。注意自带的停用词库适用的是英文文本
方法三:
还可以在分词时就利用对中文友好的结巴分词库,直接提取到文本的关键词。过滤掉非关键的词
以上三种方式:视情况自由适用。
自己手动设置停用词
使用字符串格式准备停用词比较方便 然后用结巴库分词后再转成集合得形式 当然也可以直接用集合去创建
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
txt_cut = jieba.lcut(txt_ori)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
stopwords = {'你', '呢', '又', '人', '但是', '把', '那', '就', '地', '上下', '他', '我', '吧', '会',
'一', '们', '着', '哦', '去', '什么', '了', '那么', '在', '它', '是', '这', '可是', '都',
'啊', '没', '这样', '于是', '她', '说', '不', '也', '这时', '的', '哪个', '有', '一个', '嗯', '没有','得'}
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=stopwords,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('手动指定形状和停用词词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
利用wordcloud的停用词库
发现似乎没什么效果,因为我们处理的是中文文章 所以这个代码我们就当作是了解。
(通过打印 STOPWORDS 可以看到其实 STOPWORDS 是对英文适用的)
from wordcloud import WordCloud , STOPWORDS # 导入wordcloud的停用词 STOPWORDS
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
txt_cut = jieba.lcut(txt_ori)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
# 这里直接用wordcloud的停用词 STOPWORDS
stopwords =STOPWORDS
print(STOPWORDS)
# stopwords = {'你', '呢', '又', '人', '但是', '把', '那', '就', '地', '上下', '他', '我', '吧', '会',
# '一', '们', '着', '哦', '去', '什么', '了', '那么', '在', '它', '是', '这', '可是', '都',
# '啊', '没', '这样', '于是', '她', '说', '不', '也', '这时', '的', '哪个', '有', '一个', '嗯', '没有','得'}
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=None,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('指定形状和自动停用词词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
{'a', 'during', 'both', 'those', 'what', 'any', "hadn't", 'however', "he's", 'there', 'below', 'me', "don't", 'which', 'have', 'be', 'him', 'i', 'my', 'should', "they're", 'you', 'for', 'where', 'cannot', "she's", "they'll", 'ours', 'through', 'being', 'can', "they've", 'further', "there's", 'at', "you'll", 'they', 'else', 'having', 'whom', 'shall', "she'd", 'down', "here's", 'such', 'themselves', "where's", 'does', 'before', 'do', "shan't", 'between', 'theirs', 'ourselves', "we've", 'was', 'with', 'than', "you're", "didn't", 'he', 'few', 'while', 'am', 'doing', 'into', 'just', "doesn't", 'all', 'she', 'has', 'same', 'to', 'k', "shouldn't", "wouldn't", 'on', 'http', 'is', 'hers', 'from', 'herself', 'their', "it's", 'out', 'an', "aren't", 'com', 'get', 'most', "mustn't", 'since', 'of', "when's", "weren't", 'our', "won't", 'its', 'would', 'them', 'we', "we'd", "hasn't", "we're", 'not', "they'd", "you've", 'other', 'myself', 'but', 'as', 'are', "i'd", 'off', 'and', 'so', 'yourselves', 'once', 'over', 'then', 'were', 'until', 'otherwise', 'above', "you'd", 'if', 'here', 'each', 'under', 'like', 'ought', 'this', "haven't", 'www', 'the', 'nor', "i've", 'when', "he'll", "why's", 'against', "couldn't", "that's", 'yourself', 'very', 'himself', 'yours', 'hence', "how's", 'why', 'own', 'your', "isn't", 'had', 'could', "who's", 'again', 'itself', 'these', 'about', 'also', 'no', 'only', 'been', "i'm", 'too', "i'll", 'up', 'by', 'did', 'because', 'r', "wasn't", 'who', 'that', 'ever', "let's", 'more', "he'd", 'after', 'therefore', 'or', 'some', 'in', 'his', "can't", 'it', "what's", 'how', "we'll", "she'll", 'her'}
利用jieba库提取关键词
仅使用jieba提取的关键词
需要单独导入结巴库的 另一个分析工具
import jieba.analyse
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
import jieba.analyse
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
# 注意下面代码的变化 这里是直接提取关键词的
# txt_ori 是文本内容, topK 是设置提取多少个关键词 , withWeight = False 不返回关键词的权重值
txt_cut = jieba.analyse.extract_tags(txt_ori,topK = 100,withWeight = False)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
print(txt_cut)
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=None,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('手动指定形状和停用词词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
['爱丽丝', '王后', '帽匠', '地说', '甲鱼', '鹰头狮', '公爵夫人', '睡鼠', '国王', '什么', '陪审员', '知道', '自己', '老鼠', '一只', '没有', '可是', '毛毛虫', '一个', '兔子', '他们', '回答', '这样', '三月', '于是', '白兔', '那么', '奇怪', '它们', '亲爱', '已经', '然后', '现在', '说话', '这个', '可怜', '起来', '东西', '听到', '喜欢', '这时', '声音', '但是', '红鹤', '一样', '黛娜', '地问', '的话', '砍掉', '告诉', '比尔', '因为', '非常', '如果', '多么', '我们', '继续', '急忙', '你们', '渡渡', '当然', '立即', '法庭', '高兴', '变成', '就是', '故事', '她们', '不会', '喊道', '龙虾', '希望', '一会儿', '时候', '从来', '生气', '那个', '厨师', '胳膊', '开始', '这些', '应该', '三个', '红心', '怎么', '一点', '桌子', '突然', '仆人', '看看', '好像', '全都', '奶油', '这里', '不是', '鸽子', '一定', '看着', '眼睛', '馅饼']
配合手动停用词一起使用
没有工具是万能的,但是我们人是智慧的
我们可以在结巴关键词基础上,通过观察生成的词云结果,再添加停用词 停掉一些无用的关键词,优化结果
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
import jieba.analyse
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
# 注意下面代码的变化 这里是直接提取关键词的
# txt_ori 是文本内容, topK 是设置提取多少个关键词 , withWeight = False 不返回关键词的权重值
txt_cut = jieba.analyse.extract_tags(txt_ori,topK = 100,withWeight = False)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
# print(txt_cut)
stopwords = {'地说','没有','什么','这个','于是'}
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=None,
stopwords=stopwords,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('jieba关键词和停用词词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
控制词云的颜色组成
方法一:手动设置颜色
把上面代码复制下来用 , 然后我们往里面加参数
from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
import jieba.analyse
img_mask = mping.imread('爱丽丝黑白.png')*255
# img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
# 注意下面代码的变化 这里是直接提取关键词的
# txt_ori 是文本内容, topK 是设置提取多少个关键词 , withWeight = False 不返回关键词的权重值
txt_cut = jieba.analyse.extract_tags(txt_ori,topK = 100,withWeight = False)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
# 添加颜色控制
# 颜色是我随机选的 可以自由设置 比如选择和公司logo颜色比较接近的
color_list=['#1ed1f6','#1431ff','#1484ff','#ff145e']
# 调用 然后在下面WordCloud对象参数colormap后传入即可 colormap=colormap
colormap=colors.ListedColormap(color_list)
stopwords = {'地说','没有','什么','这个','于是'}
w = WordCloud(width=640,height=480,background_color='white',
font_path='simhei',mask=img_mask,colormap=colormap,
stopwords=stopwords,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('自定义颜色词云.png')
plt.figure(figsize=(20, 8),dpi=300)
plt.imshow(w)
plt.show()
方法二:根据图片颜色自动定义词云颜色
还是根据上上面5.3.2的代码改写一个参数,color_func = image_colors,
但是图片我们用 跳舞2.png 也就是彩色的那一张,以便于观察。
利用 ImageColorGenerator 函数将词云颜色设置为根据图片颜色确定
image_colors = ImageColorGenerator(img_mask)
from wordcloud import WordCloud,ImageColorGenerator
import jieba
import matplotlib.pyplot as plt
import matplotlib.image as mping
import jieba.analyse
# img_mask = mping.imread('爱丽丝黑白.png')*255
img_mask = mping.imread('跳舞2.png')*255
with open('爱丽丝梦游仙境.txt') as f:
txt_ori = f.read()
# 注意下面代码的变化 这里是直接提取关键词的
# txt_ori 是文本内容, topK 是设置提取多少个关键词 , withWeight = False 不返回关键词的权重值
txt_cut = jieba.analyse.extract_tags(txt_ori,topK = 100,withWeight = False)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
# print(txt_cut)
stopwords = {'地说','没有','什么','这个','于是'}
# 利用 ImageColorGenerator 函数将词云颜色设置为根据图片颜色确定
image_colors = ImageColorGenerator(img_mask)
w = WordCloud(width=640,height=480,background_color='white',color_func = image_colors,
font_path='simhei',mask=img_mask,colormap=None,
stopwords=stopwords,contour_color='gray',contour_width=0,
max_font_size=80, min_font_size=2,scale = 2
)
w.generate(txt_str)
w.to_file('根据图片颜色自动定义颜色.png')
plt.figure(figsize=(10, 4),dpi=300)
plt.imshow(w)
plt.show()
希望本文档对大家有帮助,有需要,欢迎留言讨论。
王心凌《爱你》舞蹈词云视频制作
一:常规词云图绘制
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
import matplotlib.image as mping
import jieba.analyse
# 读取文本内容
with open('ge_ci.txt',encoding='utf8') as f:
txt_ori = f.read()
# 提取文本关键词数据
# txt_ori 是文本内容, topK 是设置提取多少个关键词 , withWeight = False 不返回关键词的权重值
txt_cut = jieba.analyse.extract_tags(txt_ori, topK=100, withWeight=False)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
# 可以手动设置一些停用词 即 不再词云中显示的词
stopwords = {'地说', '没有', '什么', '这个', '于是','预览'}
# 用 matplotlib 读取形状图片 图像四周的白色无用区域不会被绘制上文字
mask_file_path = '王心凌.png'
img_mask = mping.imread(mask_file_path)*255
# print(img.shape) # (1038, 835, 3) 高【1038】、宽【835】
height = img_mask.shape[0]
width = img_mask.shape[1]
# 利用 ImageColorGenerator 函数将词云颜色设置为根据图片颜色确定对应位置的文字颜色
image_colors = ImageColorGenerator(img_mask)
# 配置词云图参数
w = WordCloud(width=width, height=height, background_color='white', color_func=image_colors,
font_path='simhei', mask=img_mask, colormap=None,
stopwords=stopwords, contour_color='gray', contour_width=0,
max_font_size=80, min_font_size=2, scale=2
)
# 生成词云图
w.generate(txt_str)
# 设置保存图片的路径和新名字 规则为在原图路径文件名后面加 _多彩词云图 这几个字符
word_cloud_pic_path = mask_file_path.replace(".","_多彩词云图.")
print(word_cloud_pic_path)
# 将词云图保存到本地
w.to_file(word_cloud_pic_path)
plt.imshow(w)
plt.show()
二:将常规视频转为词云图视频
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.image as mping
import jieba.analyse
import cv2
import numpy as np
import os
import tkinter
from tkinter import filedialog,messagebox
def find_file(title,filetypes):
# 可视化打开文件夹选择文件 并返回要处理的文件路径
global Filepath
"""
对选定的具体文件路径做搜索,查找其中markdown文档并将其绝对路径传给change_file做匹配和修改
"""
root = tkinter.Tk()
root.withdraw()
# 获得选择好的文件
# Filepath = filedialog.askopenfilename(title='请选择要转换的文件', )
Filepath = filedialog.askopenfilename(title=title,initialdir=os.getcwd(),filetypes=filetypes)
if Filepath == '':
messagebox.showwarning(title="您取消了选择", message="欢迎下次使用")
return
else:
global target_file_name
# print(f'文件选择成功 => {Filepath} \n')
# file_type = os.path.splitext(Filepath)[1]
target_file_name = os.path.basename(Filepath)
print("您所选则的文件是:",target_file_name)
answer = messagebox.askquestion(title="请确认选择的文件", message= target_file_name)
if answer == "yes":
return Filepath
else:
messagebox.showinfo("欢迎下次使用","88~")
return
# 获取视频信息
def get_video_info():
global capture
old_video_path = find_file('请选择视频文件',filetypes = [("MP4","*.mp4 *.mov"),("all files","*.*")]) # 原始视频路径
# 捕获视频文件
capture = cv2.VideoCapture(old_video_path)
# 帧率
fps = int(round(capture.get(cv2.CAP_PROP_FPS)))
# 总帧数
total_frame = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
# 分辨率-宽度
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
# 分辨率-高度
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 视频的图像的尺寸 可以使用cv2.resize(图像,尺寸)进行修改
size = (width, height)
video_info = {"old_video_path":old_video_path,"fps":fps,"total_frame":total_frame,
"width":width,"height":height,"size":size}
return video_info
# 将视频转化为词云视频
def generate_wordcloud_video(text_content,video_info,start_frame=0):
# 图片数据将会从视频中不断读取并处理为词云图然后写入新的视频文件
w = WordCloud(width=video_info['width'], height=video_info['height'], background_color='white',
font_path='simhei', colormap=None, mask=None,color_func=None,
stopwords=stopwords, contour_color='gray', contour_width=0,
max_font_size=80, min_font_size=2, scale=1
)
# 创建视频编辑对象.avi 文件
new_video_path = video_info['old_video_path'].replace(".", "_词云视频.") # 将来要存储的新视频路径
new_video = cv2.VideoWriter(new_video_path, cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),
video_info['fps'], video_info['size'])
# 当前帧数
current_frame = start_frame
# 设置跳转到的具体帧数
capture.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
# 定义用于展示画面的窗口 设置名字 和 可调节大小的属性
window_name = "video_to_wordcloud_pic"
cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) # 支持手动调节大小
# cv2.namedWindow('window_name2', cv2.WINDOW_AUTOSIZE) # 默认原图大小
while capture.isOpened():
ret, frame = capture.read() # 每次循环都会去读取下一帧图像
if ret: # 如果读取到了图片
img_mask = ~frame # 图像反色 原图中没有人物的区域都是黑色 反色后变为白色 不再被词云绘制
# 利用 ImageColorGenerator 函数将词云颜色设置为根据图片颜色确定
image_colors = ImageColorGenerator(frame)
# 更新词云图的参数
w.mask = img_mask
w.color_func = image_colors
w.generate(text_content)
# w.to_file('根据图片颜色自动定义词云颜色.png') # 将词云保存到本地
num_array_img = w.to_array() # 将词云图片转化成numpy数组形式供opencv使用
print('当前处理进度:', current_frame, "/", video_info['total_frame'],"按 Esc 可停止")
current_frame += 1 # 将记录进度的数字加 1
# 将新的词云图片添加到入视频中
new_video.write(num_array_img)
# 展示多张图片
# 使用numpy的水平堆叠和竖直堆叠完成所有图像的堆叠,最后多张图在一个画面中一起显示
if frame.shape[0] < frame.shape[1]: # 如果图片是高的
result = np.hstack((frame, num_array_img)) # 水平堆叠
else: # 如果图片是宽的
result = np.vstack((frame, num_array_img)) # 竖直堆叠
cv2.imshow(window_name, result)
c = cv2.waitKey(20)
if c == 27: # 当键盘按下‘ESC’退出程序 结束视频的写入
new_video.release()
cv2.destroyAllWindows()
print('程序被主动操作结束 按下了esc')
break
else:
new_video.release()
cv2.destroyAllWindows()
print('~~~~~~~~~~程序处理完毕~~~~~~~~~文件保存在原视频同名目录下')
def get_text_content():
text_file_path = find_file('请选择文本',filetypes = [("TXT","*.txt"),("all files","*.*")])
# 读取文本内容
with open(text_file_path, encoding='utf8') as f:
txt_ori = f.read()
# 提取文本关键词数据
# txt_ori 是文本内容, topK 是设置提取多少个关键词 , withWeight = False 不返回关键词的权重值
txt_cut = jieba.analyse.extract_tags(txt_ori, topK=100, withWeight=False)
# 记得这里字符串是由空格拼接列表得到得 引号中间有个空格
txt_str = " ".join(txt_cut)
return txt_str
if __name__ == "__main__":
# 可以手动设置一些停用词 即 不再词云中显示的词
stopwords = {'地说', '没有', '什么', '这个', '于是', '预览', '歌词', '专辑', 'LRC歌词', '搜索', '打印', 'LRC', 'mp3'}
text_content = get_text_content()
video_info = get_video_info()
generate_wordcloud_video(text_content,video_info, start_frame=120)