数据分析可视化系列(五)弹幕词云图
发布时间
阅读量:
阅读量
弹幕词云图
-
使用的词云库
-
核心代码
-
-
1. 正则表达式
-
2. 标准库
-
- 多维数组转换为一维数组
-
3. 词云库
-
4. pandas库
-
-
完整代码
-
结果截图
使用的词云库
- jieba中文分词库
- wordcloud词云库
核心代码
1. 正则表达式
| 方法 | 函数 | 备注 |
|---|---|---|
| re.compile(pattern) | 编译 | |
| re.sub(repl, string) | 替换 | repl:编译对象,string:文本 |
2. 标准库
多维数组转换为一维数组
from itertools import chain
list_2d = [[1,2,3],[3,4,5]]
list_1d = list(chain.from_iterable(li_2d))
print(list_1d)

3. 词云库
WordCloud
font_path: 字体路径, width 图像宽度, height 图像高度, max_words 最大词语数量 , background_color 背景颜色(其他参数请自行查找)
wc = WordCloud(font_path=r"C:/Windows/Fonts/SimHei.ttf", width=800, height=600, max_words=50,
background_color="white")
# 根据词频制作词云图,可以减少重复词
# c: 是一个字典
img = wc.generate_from_frequencies(c)
plt.figure(figsize=(9, 6))
plt.axis("off")
plt.imshow(img)
plt.show()
4. pandas库
完整代码
import re
from collections import Counter
from itertools import chain
import jieba
import matplotlib.pyplot as plt
import pandas as pd
from wordcloud import WordCloud
pattern = "[,!\"#, -. : ; <=>^_`~!,。?、¥… ():【《》‘’“”\s]+"
# 预编译,减少重复匹配
re_obj = re.compile(pattern)
def clear(text):
"使用编译的模式(提高效率):替换弹幕中的所有符号"
return re_obj.sub("", text,)
def get_stopword():
"使用集合来获取停用词表的词组"
s = set()
with open(r"./百度停用词表.txt", encoding="utf-8") as f:
for line in f:
s.add(line.strip()) # 去掉每行末尾的换行符
return s
def remove_stopword(words):
"删除分词结果中含有停用词表的词组"
stopword = get_stopword()
return [word for word in words if word not in stopword]
# 黑体显示中文字体
plt.rcParams["font.family"] = "SimHei"
# 显示负号
plt.rcParams["axes.unicode_minus"] = False
# 读取csv文件
df = pd.read_csv("./2021-01-19弹幕池.csv")
data = df.copy()
# 链式函数
# 先替换所有标点符号
# 再通过jieba分词获得列表
# 最后删除在停用词表中的词语
data["内容"] = data["内容"].apply(lambda x: re_obj.sub("", x)).apply(
lambda x: jieba.cut(x)).apply(remove_stopword)
# print(data["内容"])
# print(data.sample(10))
# Series对象转换为列表
li_2d = data["内容"].tolist()
# 将二维列表扁平化为一维列表
li_1d = list(chain.from_iterable(li_2d))
print(f"总词汇量:{len(li_1d)}")
# Counter用于统计
c = Counter(li_1d)
print(f"不重复词汇数量:{len(c)}")
common = c.most_common(15)
print(f"词频排名在前15名:{common}")
# 词频统计
vocabulary, frequency = [], []
for v, f in common:
vocabulary.append(v)
frequency.append(f)
# 绘制柱状图
plt.figure(figsize=(12, 5))
plt.title("排名前15的词")
plt.bar(vocabulary, frequency)
# 需要指定字体的位置,否则中文无法正常显示。
wc = WordCloud(font_path=r"C:/Windows/Fonts/SimHei.ttf", width=800, height=600, max_words=50,
background_color="white")
# 根据词频制作词云图,可以减少重复词
img = wc.generate_from_frequencies(c)
plt.figure(figsize=(9, 6))
plt.axis("off")
plt.imshow(img)
plt.show()
结果截图



全部评论 (0)
还没有任何评论哟~
