视频弹幕词云图生成器

根据B站视频链接生成当前视频的弹幕云图。目前只支持B站,后续会添加爱奇艺、腾讯视频等其他平台。
可在代码中引入调用或命令行调用,也可以直接修改代码使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
引入调用
import
wc_builder
as
ww
ww.main(
'https://www.bilibili.com/video/BV1EK411o7iV'
)
命令行调用
python .\wc_builder.py https://www.bilibili.com/video/BV1EK411o7iV
Building prefix
dict
from
the default dictionary ...
Loading model
from
cache C:\Users\V\AppData\Local\Temp\jieba.cache
Loading model cost
.532
seconds.
Prefix
dict
has been built successfully.
修改代码调用
if
__name__ ==
'__main__'
:
main(
'https://www.bilibili.com/video/BV1EK411o7iV'
)
# main(sys.argv[1])

初始代码如下。
代码比较粗糙,有空再研究下弹幕的数量、去重。(B站的弹幕有很多重复的,例如“哈哈哈”和‘哈哈哈哈’这种文本在wordcloud中就是两个词,生成出来的词云图会出现很多重复但字数不同的文本)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import
re
import
sys
import
jieba
from
wordcloud
import
WordCloud
import
requests
# 词云生成器父类
class
wc_builder
:
def
__init__
(
self
) ->
None
:
pass
def
wordcloud_builder
(
self, param
):
raise
Exception(
'Wordcloud_builder Not Implemented'
)
# bilibili弹幕词云生成器,video_links为B站视频链接
class
bl_builder
(
wc_builder
):
def
wordcloud_builder
(
self, param
):
# 检测链接格式
if
(
'https://www.bilibili.com/video/'
not
in
param) & (requests.get(param).status_code !=
):
raise
Exception(
'The video links is Wrong'
)
# 获取视频cid
video_context = requests.get(param).text
cid = re.
compile
(
r'"cid":(\d{9}),"dimension"'
).findall(
video_context)[
]
# 拼接弹幕地址并获取弹幕文件
new_links =
'https://api.bilibili.com/x/v1/dm/list.so?oid='
+cid
dm = requests.get(new_links)
dm.encoding =
'utf-8'
# 解析本地弹幕文件,已废弃,直接从接口获取
# with open("tools/files/tc.xml", "rb") as f:
# dm = f.read()
# ndm = dm.decode('utf-8')
# 过滤弹幕文本
match
= re.
compile
(
r">(.*?)</d>"
).findall(dm.text)
mstr =
'.'
.join(
match
)
words = jieba.lcut(mstr)
newtext =
''
.join(words)
# 去除不可见字符, 这一步可忽略,一般用于过滤带特殊字符的文本
# newtext = re.sub(
'[\001\002\003\004\005\006\007\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a]+'
,
''
, newtext)
# 使用黑体字体支持中文
wordcloud = WordCloud(
font_path=
"../tools/files/SimHei.ttf"
).generate(newtext)
#2种方式查看词云。1:直接在本地生成词云图片
wordcloud.to_file(
'弹幕词云图.png'
)
# 2. 通过matplotlib生成图片
import
matplotlib.pyplot
as
plt
plt.imshow(wd, interpolation=
'bilinear'
)
#interpolation='bilinear' 表示插值方法为双线性插值
plt.axis(
"off"
)
# 关掉图像的坐标
plt.show()
def
main
(
parm
):
ss = bl_builder()
ss.wordcloud_builder(parm)
# 该方式有待优化。直接运行该文件时会提示缺少参数,外部调用时需手动填入参数
if
__name__ ==
'__main__'
:
# main('https://www.bilibili.com/video/BV1EK411o7iV')
main(sys.argv[
])

img


视频弹幕词云图生成器
https://zhouyinglin.top/2022/12/15/视频弹幕词云图生成器/
作者
小周
发布于
2022年12月15日
许可协议