Bilibili数据分析 B站爬虫|Bilibili 弹幕信息情感分析 Snow NLP 情感词典

需求分析

该代码旨在分析B站视频弹幕数据,包括情绪分类、情感分析和按秒计算弹幕数量。分析结果将作为一个CSV文件保存。

功能介绍

  1. 读取弹幕文件和词库文件。
  2. 对弹幕内容进行清洗和分词。
  3. 对弹幕进行情绪分类和情感分析。
  4. 按秒计算每个弹幕的情绪数量和情感得分。
  5. 将分析结果保存为CSV文件。

重点代码介绍

  1. 定义了document_to_list()函数,用于将文档内容读取为列表。

  2. 定义了clean_text()函数,用于对弹幕内容进行清洗。

  3. 定义了count()函数,用于计算每个弹幕的情绪数量。

  4. 定义了sentiment_score()函数,用于计算每个弹幕的情感得分。

  5. 定义了Analyze()函数,用于分析弹幕数据并将结果保存为CSV文件。

  6. 清理文本

def clean_text(text):
    # 使用正则表达式删除特殊字符
    text = re.sub(r"[^\w\s]", "", text)
    emoji_pattern = re.compile("["
                               u"\U0001F600-\U0001F64F"  # emoticons
                               u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                               u"\U0001F680-\U0001F6FF"  # transport & map symbols
                               u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                               u"\U00002702-\U000027B0"
                               "]+", flags=re.UNICODE)
    text = emoji_pattern.sub(r'', text)
    return text.strip()

这个函数用于清理文本,去除特殊字符和表情符号,使得分析过程更加准确。

  1. 计算情绪
def count(cut_list):
    emo_cnt = {
   "anger": 0, "disgust": 0, "fear": 0, "joy": 0, "sadness": 0}
    danmuku_emotion = []
    for word in cut_list:
        if word in anger:
            emo_cnt["anger"] += 1
        if word in disgust:
            emo_cnt["disgust"] += 1
        if word in fear:
            emo_cnt["fear"] += 1
        if word in joy:
            emo_cnt["joy"] += 1
        if word in sadness:
            emo_cnt["sadness"] += 1

    emo_max = max(emo_cnt.values())

    if emo_max == 0:
        danmuku_emotion.append("none")
    else:
        for key, value in emo_cnt.items():
            if value == emo_max:
                danmuku_emotion.append(key)

    if len(danmuku_emotion) == 1:
        danmuku_emotion = danmuku_emotion[0]
    else
  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫获取B站弹幕数据分析可以分为以下几个步骤: 1. 获取B站视频的cid,可以通过视频页面的URL来获取,例如视频页面的URL为:https://www.bilibili.com/video/BV1QK4y1d7dK,则cid为BV1QK4y1d7dK。 2. 使用B站提供的弹幕API获取弹幕数据,可以使用requests库发送请求,然后解析返回的XML数据,获取弹幕文本内容和发送时间等信息。 3. 将弹幕数据保存到本地文件或数据库中,可以使用csv、json、sqlite等格式进行存储。 4. 数据分析和可视化,可以使用pandas、matplotlib、seaborn等库进行数据分析和可视化,例如统计弹幕数量和分布、分析弹幕关键词等。 下面是一份获取B站视频弹幕并进行数据分析的示例代码: ```python import requests from bs4 import BeautifulSoup import xml.etree.ElementTree as ET import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 获取视频cid url = 'https://www.bilibili.com/video/BV1QK4y1d7dK' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') cid = soup.find('meta', {'itemprop': 'videoId'})['content'] # 获取弹幕数据 danmu_url = f'https://api.bilibili.com/x/v1/dm/list.so?oid={cid}' response = requests.get(danmu_url) xml_data = response.content.decode('utf-8-sig') xml_root = ET.fromstring(xml_data) danmu_list = [] for danmu in xml_root.iter('d'): danmu_attr = danmu.attrib['p'].split(',') danmu_list.append({ 'time': float(danmu_attr[0]), 'mode': int(danmu_attr[1]), 'color': int(danmu_attr[3]), 'text': danmu.text.strip() }) # 保存弹幕数据到csv文件中 df = pd.DataFrame(danmu_list) df.to_csv('danmu.csv', index=False, encoding='utf-8-sig') # 数据分析和可视化 df['datetime'] = pd.to_datetime(df['time'], unit='s') df['date'] = df['datetime'].dt.date df['hour'] = df['datetime'].dt.hour df['minute'] = df['datetime'].dt.minute df['second'] = df['datetime'].dt.second df['count'] = 1 # 统计弹幕数量和分布 danmu_count = df.groupby('date')['count'].sum() danmu_count.plot(kind='line', title='B站弹幕数量趋势', figsize=(8, 4)) plt.show() danmu_hour_count = df.groupby('hour')['count'].sum() danmu_hour_count.plot(kind='bar', title='B站弹幕小时分布', figsize=(8, 4)) plt.show() # 分析弹幕关键词 from jieba.analyse import extract_tags keywords = extract_tags(df['text'].str.cat(sep=' '), topK=20, withWeight=True) df_keywords = pd.DataFrame(keywords, columns=['keyword', 'weight']) sns.barplot(x='weight', y='keyword', data=df_keywords) plt.title('B站弹幕关键词分析') plt.show() ``` 以上代码可以获取B站视频的弹幕数据,并对弹幕数据进行数量和分布统计、关键词分析等操作,并使用pandas、matplotlib和seaborn等库进行数据分析和可视化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值