你认可《后浪》吗

时间:2022-07-23
本文章向大家介绍你认可《后浪》吗,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前几天 B 站上线了一个小视频《后浪》,在全网引起了热烈反响,有赞扬也有批评,视频地址:https://www.bilibili.com/video/BV1FV411d7u7,本文我们爬一下视频弹幕来了解一下 B 站网友对视频的看法。

视频弹幕是存在 xml 文件中的,链接的格式为:http://comment.bilibili.com/+cid+.xml,我们只需要拿到视频的 cid 即可,看一下获取方式,我们先打开视频链接 https://www.bilibili.com/video/BV1FV411d7u7,接着按 F12 键打开开发者工具选择 Network,再刷新一下页面,我们到 Filter 中输入 cid 即可,如下所示:

拿到了 cid,我们可以知道弹幕文件链接为:http://comment.bilibili.com/186803402.xml,打开链接看一下:

弹幕爬取的实现代码如下所示:

url = "http://comment.bilibili.com/186803402.xml"
req = requests.get(url)
html = req.content
html_doc = str(html, "utf-8")  # 修改成utf-8
# 解析
soup = BeautifulSoup(html_doc, "lxml")
results = soup.find_all('d')
contents = [x.text for x in results]
# 保存结果
dic = {"contents": contents}
df = pd.DataFrame(dic)
df["contents"].to_csv("bili.csv", encoding="utf-8", index=False)

现在我们已经获取了弹幕数据,接下来再对数据做个词云展示,实现代码如下所示:

def jieba_():
    # 打开评论数据文件
    content = open("bili.csv", "rb").read()
    # jieba 分词
    word_list = jieba.cut(content)
    words = []
    # 过滤掉的词
    stopwords = open("stopwords.txt", "r", encoding="utf-8").read().split("n")[:-1]
    for word in word_list:
        if word not in stopwords:
            words.append(word)
    global word_cloud
    # 用逗号隔开词语
    word_cloud = ','.join(words)

def cloud():
    # 打开词云背景图
    cloud_mask = np.array(Image.open("bg.png"))
    # 定义词云的一些属性
    wc = WordCloud(
        # 背景图分割颜色为白色
        background_color='white',
        # 背景图样
        mask=cloud_mask,
        # 显示最大词数
        max_words=500,
        # 显示中文
        font_path='./fonts/simhei.ttf',
        # 最大尺寸
        max_font_size=60,
        repeat=True
    )
    global word_cloud
    # 词云函数
    x = wc.generate(word_cloud)
    # 生成词云图片
    image = x.to_image()
    # 展示词云图片
    image.show()
    # 保存词云图片
    wc.to_file('cloud.png')

看一下效果: