-
2021-09-05 19:14:31
文章目录
1.所需库
2.cid的获取
3.源代码1.所需库
- requests:用于发送http请求
- BeautifulSoup:用于解析html文档,便于之后的到导航和查找
- pandas:用于对数据的处理,创建数据电子表格
2.cid的获取:
点击F12在右端获取
3.源代码如下:
import numpy as np from PIL import Image from bs4 import BeautifulSoup url="http://comment.bilibili.com/cid.xml" req = requests.get(url) html=req.content html_doc = str(html,"utf-8") #解析 soup = BeautifulSoup(html_doc,'html.parser') results = soup.find_all('d') #x.text表示要放到contents中的值 contents = [x.text for x in results] #保存结果 dic ={"contents" : contents} #用字典创建了一个电子表格 df = pd.DataFrame(dic) #把内容写到bili.csv中 df["contents"].to_csv("hetongxue.csv",encoding="utf-8",index=False)
更多相关内容 -
python爬虫工具_B站弹幕爬取
2021-10-30 21:37:02运行程序,输入Bvid和爬取日期;程序运行完成后会在当前文件夹下生成一个csv格式文件。 -
python爬虫b站三国演义全集弹幕
2022-06-12 20:38:40python爬虫b站三国演义全集弹幕 -
Python爬虫爬取Bilibili弹幕过程解析
2020-09-18 14:21:55主要介绍了Python爬虫爬取Bilibili弹幕过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 -
Python爬虫之bilibili视频弹幕爬取并保存为JSON格式(详解+代码实现)
2020-12-22 13:29:48今天我们的爬虫内容是bilibili视频弹幕爬取,并保存到本地为JSON格式,正常爬虫只需要发送请求,解析相应内容,而爬取bilibili的内容,视频弹幕并没在响应的html中,而是保存在一个响应的url中,以XML格式保存,... -
B站弹幕抓取2021.zip
2021-09-28 00:00:26抓取B站弹幕数据。 弹幕dmid,唯一 可用于操作参数 视频内弹幕出现时间,毫秒 弹幕类型,1 2 3:普通弹幕 4:底部弹幕 5:顶部弹幕 6:逆向弹幕 7:高级弹幕 8:代码弹幕 9:BAS弹幕(仅限于特殊弹幕专包) 弹幕字号... -
python爬取B站视频中的弹幕并图形化展示
2020-11-26 17:46:33python爬取B站视频中的弹幕并图形化展示 新手上路,参考:https://blog.csdn.net/csdnnews/article/details/106754771案例 需要了解爬取的地址: 1:视频地址:https://www.bilibili.com/video/BV1PK4y1b7dt?t=1 2....python爬取B站视频中的弹幕并图形化展示
新手上路,参考:https://blog.csdn.net/csdnnews/article/details/106754771案例
需要了解爬取的地址:
1:视频地址:https://www.bilibili.com/video/BV1PK4y1b7dt?t=1
2.对于参考文档中提到的B站API接口,是如何找到的,不是很清楚,故只能照搬过来:https://api.bilibili.com/x/v1/dm/list.so?oid=XXX,其中XXX需要在网页中获取
3.oid=XXX中的XXX获取:
获取cid:https://api.bilibili.com/x/player/pagelist?bvid=BV1PK4y1b7dt&jsonp=json
此处的cid,即所需XXX,如果视频是分段的,则会有多个cid值,这里只有一个
故完整的接口为:https://api.bilibili.com/x/v1/dm/list.so?oid=201056987
代码:我这是分两部分,爬取弹幕保存本地,本地读取构成词云图
本地爬取:import requests import json import re import chardet #提供自动检测字符编码的功能 from pprint import pprint #打印出任何python数据结构类的和方法,没用到 from wordcloud import wordcloud #是一种将词语用图片表达出来的一种形式 '''根据bvid请求得到cid''' def get_cid(): #视频地址:https://www.bilibili.com/video/BV1PK4y1b7dt?t=1 url='https://api.bilibili.com/x/player/pagelist?bvid=BV1PK4y1b7dt&jsonp=jsonp' res=requests.get(url).text #将获取的网页json编码字符串转换为python对象 json_dict=json.loads(res) return json_dict["data"][0]["cid"] '''根据cid请求弹幕,并解析所得数据''' def get_data(cid): #https://api.bilibili.com/x/v1/dm/list.so?oid=XXX #最终爬取API:https://api.bilibili.com/x/v1/dm/list.so?oid=201056987 try: final_url="https://api.bilibili.com/x/v1/dm/list.so?oid="+str(cid) final_res=requests.get(final_url) final_res.encoding='utf-8' final_res_encoding=chardet.detect(final_res.content) final_res=final_res.text pattern=re.compile('<d.*?>(.*?)</d>') data=pattern.findall(final_res) print(u"获取的data=",data) return data except Exception as e: print("执行get_data失败:",e) '''保存弹幕列表''' def save_to_file(data): try: with open('zjl_mv.txt',mode="w",encoding='utf-8') as f: for i in data: f.write(i) f.write("\n") f.close() except Exception as e: print ("执行保存文件报错:",e)
构成词云图:
import pandas as pd #用于数据导入及整理模块,对数据挖掘前期数据的处理 import jieba #用于中文分词的模块,名为结巴分词库 from wordcloud import wordcloud #是一种将词语用图片表达出来的一种形式 import matplotlib.pyplot as plt #python的绘图库 from imageio import imread #提供一个接口来读取和写入大量的图像数据 import warnings '''忽略匹配的警告''' warnings.filterwarnings("ignore") '''将文本进行分词''' def cut(): try: with open('zjl_mv.txt',encoding='utf-8') as f: text=f.read() #text=text.replace('#后台播放','').replace('!','').replace('#','').split() #以空格、\n为分隔符对text进行切片,是一个列表 text=text.replace('#后台播放',' ').replace('后台播放',' ').split() #以空格、\n为分隔符对text进行切片,是一个列表 print("text=",text) jieba.suggest_freq('小公举',True) #使得小公举这个词不被拆分 data_cut=[jieba.lcut(x) for x in text if '\n' not in x] #返回的是对X进行分词的列表,X print("data_cut=",data_cut) '''词频统计''' all_words=[] for i in data_cut: all_words.extend(i) #将分词列表合成一个新的列表展示 word_count=pd.Series(all_words).value_counts() #返回一个包含所有值及其出现次数的Series,且为降序输出 #print("排序分词:",word_count) f.close() return word_count except Exception as e: print("分词出错",e) return 1 '''词云图的制作''' def citu(data_cut): try: bj_picture=imread(r"D:\code\pytest3\img\bj.jpg") #读取背景图 '''设置词云参数''' wc=wordcloud.WordCloud(font_path="G:\\6Tipdm\\wordcloud\\simhei.ttf", background_color="white", max_words=2000, mask=bj_picture, max_font_size=100, random_state=42) wc2=wc.fit_words(data_cut) '''绘制图云图片''' plt.figure(figsize=(10,6)) plt.imshow(wc2) plt.axis("off") plt.show() wc.to_file("ciyun.png") except Exception as e: print("词云图制作报错:",e)
最终效果:
总结:
1.json数据格式的使用,request获取的text,一般都是就json数据格式,需要使用json.loads(text)函数将就json编码格式转换程序python对象,反之可以使用json.dumps(text);
2.精准数据获取:针对json编码转python对象,json的object、array、string、number(ini)、number(real)、true、false、null分别对应python的dict、list、Unicode、int/long、float、True、False、None,可以根据python的各类操作进行数据获取
3.乱码问题:发送request.get请求得到的text文本,打印出现乱码问题,可以通过在发送request.get请求返回的response对象指明编码方式,再去获取text属性,如下图:
用到的知识:
1.jieba库:用于中文分词的模块;
涉及的函数:jieba.lcut(s)–精确模式,返回一个列表类型,其中s是一个字符串;ps:具体用法参考:https://blog.csdn.net/qq_34337272/article/details/79554772
2.学到一个语句:其中text是一个字符串列表,得到的data_cut还是一个列表
3.pandas库:数据分析工具;
用到了series(),能够保存任何类型的数据,以一维标记数据(相当于字典),区别在于,默认通过(0,n-1)作为key访问数据,也可以自己定义key,例如:obj=pd.Series([1,3,8,24,23],index=[‘a’,‘b’,‘c’,‘d’,‘e’]),通过a/b/c/d/e作为索引
4.词云这块没做细究,纯属搬运工 -
用Python爬取B站弹幕并做成词云
2021-06-19 21:37:49用Python爬取B站弹幕并做成词云 一、获取视频的cid号 1.进入想爬的视频,打开浏览器设置里的“开发者工具”: 进入Search后输入cid获得视频的cid号。 2.爬视频的弹幕 #爬数据正文 def get_data(cid): # 分析网页,...用Python爬取B站弹幕并做成词云
一、获取视频的cid号
1.进入想爬的视频,打开浏览器设置里的“开发者工具”:
进入NetWork后等待requests刷出,数据够了后可随意点击一个数据查看其preview和其URL,
然后进入Search后输入cid获得视频的cid号。2.爬视频的弹幕
#爬数据正文 def get_data(cid): # 分析网页,并获取网页文件 url = 'https://comment.bilibili.com/{}.xml'.format(cid) #B站弹幕数据存放在https://comment.bilibili.com/cid.xml中,其中cid是视频的cid号 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/80.0.3987.163Safari/537.36" } response = requests.get(url,headers = headers).content.decode('utf-8') return response def parse_html(response): # 解读网页文件,获取关键信息 # soup = bs4.BeautifulSoup(response) # lst = [soup.find_all(name='d')] # danmuku = [i.text for i in lst] pattern = re.compile(r'<d p=".*?">(.*?)</d>') danmuku = re.findall(pattern,response) #print(danmuku) #打印弹幕数据 return danmuku def save_data(danmuku,cid): # 保存数据 Dict = { 'danmuku' : danmuku } pd_data = pd.DataFrame(Dict) cid = str(cid) name = cid + '弹幕文件.txt' path = 'C:/Users/priesty/Desktop/弹幕数据/{}'.format(name) pd_data.to_csv(path,index = False,header=False,mode='w',encoding='utf-8-sig') def data_preprocess(danmuku,cid): cid = str(cid) name = cid + '弹幕文件.txt' path = 'C:/Users/priesty/Desktop/弹幕数据/{}'.format(name) with open(path ,mode='r',encoding='utf-8') as f: # 加载用户自定义字典 jieba.load_userdict (r'C:/Users/priesty/Desktop/弹幕数据/自定义词表.txt') reader = f.read().replace('\n','') # 加载停用词词表 stopwords = [line.strip() for line in open(r'C:/Users/priesty/Desktop/弹幕数据/停用词表.txt',encoding ='utf8').readlines()] #原代码为gbk,改为了utf8 # 去标点,去数字,去空白 pun_num = string.punctuation + string.digits table = str.maketrans('','',pun_num) reader = reader.translate(table) seg_list = jieba.cut(reader,cut_all=False) sentence = '' for word in seg_list: if word not in stopwords and word.isspace() == False: sentence += word sentence += ',' sentence = sentence[:-1] return sentence def count_words(txt,cid): cid = str(cid) name = cid + '弹幕词汇数统计.txt' path = 'C:/Users/priesty/Desktop/弹幕数据/{}'.format(name) aDict = {} words = txt.split(',') for word in words: aDict[word] = aDict.get(word,0) + 1 pd_count = pd.DataFrame(aDict,index=['times']).T.sort_values('times',ascending=False) pd_count.to_csv(path) if __name__ == "__main__": cid = int(input('请输入你想查询的视频CID号:')) response = get_data(cid) #这两句可改为一句response = get_data(348133155) danmuku = parse_html(response) save_data(danmuku,cid) sentence = data_preprocess(danmuku,cid) count_words(sentence,cid)
原代码来自:https://blog.csdn.net/paxiaochong001/article/details/116937710
ps:1.“自定义词表”和“停用词表”内容可以随便添加
2.B站弹幕数据存放在https://comment.bilibili.com/cid.xml中,其中cid是视频的cid号
3.路径的斜杠别用反了3.制作词云
安装jieba、wordcloud、request库(后两个基本上新版自带)#词云正文 #背景图 bg=np.array(Image.open("C:/Users/priesty/Desktop/弹幕数据/1.png")) #获取当前的项目文件加的路径 d=path.dirname('__file__') #file要加引号 #d=os.path.abspath('') #读取停用词表 stopwords_path='C:/Users/priesty/Desktop/弹幕数据/停用词表.txt' #添加需要自定以的分词 jieba.add_word("晚唐") jieba.add_word("武周") #读取要分析的文本 text_path="C:/Users/priesty/Desktop/弹幕数据/348133155弹幕文件.txt" #文本太大读取不出来 #读取要分析的文本,读取格式 text=open(path.join(d,text_path),encoding="utf8").read() #定义个函数式用于分词 def jiebaclearText(text): #定义一个空的列表,将去除的停用词的分词保存 mywordList=[] #进行分词 seg_list=jieba.cut(text,cut_all=False) #将一个generator的内容用/连接 listStr='/'.join(seg_list) #打开停用词表 f_stop=open(stopwords_path,encoding="utf8") #读取 try: f_stop_text=f_stop.read() finally: f_stop.close()#关闭资源 #将停用词格式化,用\n分开,返回一个列表 f_stop_seg_list=f_stop_text.split("\n") #对默认模式分词的进行遍历,去除停用词 for myword in listStr.split('/'): #去除停用词 if not(myword.split()) in f_stop_seg_list and len(myword.strip())>1: mywordList.append(myword) return ' '.join(mywordList) text1=jiebaclearText(text) #生成 wc=WordCloud( background_color="white", max_words=200, mask=bg, #设置图片的背景 max_font_size=60, random_state=42, font_path='C:/Windows/Fonts/simkai.ttf' #中文处理,用系统自带的字体 ).generate(text1) #为图片设置字体 my_font=fm.FontProperties(fname='C:/Windows/Fonts/simkai.ttf') #产生背景图片,基于彩色图像的颜色生成器 image_colors=ImageColorGenerator(bg) #开始画图 plt.imshow(wc.recolor(color_func=image_colors)) #为云图去掉坐标轴 plt.axis("off") #画云图,显示 plt.figure() #为背景图去掉坐标轴 plt.axis("off") plt.imshow(bg,cmap=plt.cm.gray) #保存云图 wc.to_file("C:/Users/priesty/Desktop/弹幕数据/2.png")
原代码来自:https://piqiandong.blog.csdn.net/article/details/79558589
则词云图片为:
4.整个原代码#爬数据前缀 import requests import re import pandas as pd import string import jieba #词云前缀 from os import path #用来获取文档的路径 from PIL import Image import numpy as np import matplotlib.pyplot as plt #词云生成工具 from wordcloud import WordCloud,ImageColorGenerator #需要对中文进行处理 import matplotlib.font_manager as fm #爬数据正文 def get_data(cid): # 分析网页,并获取网页文件 url = 'https://comment.bilibili.com/{}.xml'.format(cid) #B站弹幕数据存放在https://comment.bilibili.com/cid.xml中,其中cid是视频的cid号 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/80.0.3987.163Safari/537.36" } response = requests.get(url,headers = headers).content.decode('utf-8') return response def parse_html(response): # 解读网页文件,获取关键信息 # soup = bs4.BeautifulSoup(response) # lst = [soup.find_all(name='d')] # danmuku = [i.text for i in lst] pattern = re.compile(r'<d p=".*?">(.*?)</d>') danmuku = re.findall(pattern,response) #print(danmuku) #打印弹幕数据 return danmuku def save_data(danmuku,cid): # 保存数据 Dict = { 'danmuku' : danmuku } pd_data = pd.DataFrame(Dict) cid = str(cid) name = cid + '弹幕文件.txt' path = 'C:/Users/priesty/Desktop/弹幕数据/{}'.format(name) pd_data.to_csv(path,index = False,header=False,mode='w',encoding='utf-8-sig') def data_preprocess(danmuku,cid): cid = str(cid) name = cid + '弹幕文件.txt' path = 'C:/Users/priesty/Desktop/弹幕数据/{}'.format(name) with open(path ,mode='r',encoding='utf-8') as f: # 加载用户自定义字典 jieba.load_userdict (r'C:/Users/priesty/Desktop/弹幕数据/自定义词表.txt') reader = f.read().replace('\n','') # 加载停用词词表 stopwords = [line.strip() for line in open(r'C:/Users/priesty/Desktop/弹幕数据/停用词表.txt',encoding ='utf8').readlines()]#原代码为gbk,改为了utf8 # 去标点,去数字,去空白 pun_num = string.punctuation + string.digits table = str.maketrans('','',pun_num) reader = reader.translate(table) seg_list = jieba.cut(reader,cut_all=False) sentence = '' for word in seg_list: if word not in stopwords and word.isspace() == False: sentence += word sentence += ',' sentence = sentence[:-1] return sentence def count_words(txt,cid): cid = str(cid) name = cid + '弹幕词汇数统计.txt' path = 'C:/Users/priesty/Desktop/弹幕数据/{}'.format(name) aDict = {} words = txt.split(',') for word in words: aDict[word] = aDict.get(word,0) + 1 pd_count = pd.DataFrame(aDict,index=['times']).T.sort_values('times',ascending=False) pd_count.to_csv(path) if __name__ == "__main__": cid = int(input('请输入你想查询的视频CID号:')) response = get_data(cid) #这两句可改为一句response = get_data(348133155) danmuku = parse_html(response) save_data(danmuku,cid) sentence = data_preprocess(danmuku,cid) count_words(sentence,cid) #词云正文 #背景图 bg=np.array(Image.open("C:/Users/priesty/Desktop/弹幕数据/1.png")) #获取当前的项目文件加的路径 d=path.dirname('__file__') #file要加引号 #d=os.path.abspath('') #读取停用词表 stopwords_path='C:/Users/priesty/Desktop/弹幕数据/停用词表.txt' #添加需要自定以的分词 jieba.add_word("晚唐") jieba.add_word("武周") #读取要分析的文本 text_path="C:/Users/priesty/Desktop/弹幕数据/348133155弹幕文件.txt" #文本太大读取不出来 #读取要分析的文本,读取格式 text=open(path.join(d,text_path),encoding="utf8").read() #定义个函数式用于分词 def jiebaclearText(text): #定义一个空的列表,将去除的停用词的分词保存 mywordList=[] #进行分词 seg_list=jieba.cut(text,cut_all=False) #将一个generator的内容用/连接 listStr='/'.join(seg_list) #打开停用词表 f_stop=open(stopwords_path,encoding="utf8") #读取 try: f_stop_text=f_stop.read() finally: f_stop.close()#关闭资源 #将停用词格式化,用\n分开,返回一个列表 f_stop_seg_list=f_stop_text.split("\n") #对默认模式分词的进行遍历,去除停用词 for myword in listStr.split('/'): #去除停用词 if not(myword.split()) in f_stop_seg_list and len(myword.strip())>1: mywordList.append(myword) return ' '.join(mywordList) text1=jiebaclearText(text) #生成 wc=WordCloud( background_color="white", max_words=200, mask=bg, #设置图片的背景 max_font_size=60, random_state=42, font_path='C:/Windows/Fonts/simkai.ttf' #中文处理,用系统自带的字体 ).generate(text1) #为图片设置字体 my_font=fm.FontProperties(fname='C:/Windows/Fonts/simkai.ttf') #产生背景图片,基于彩色图像的颜色生成器 image_colors=ImageColorGenerator(bg) #开始画图 plt.imshow(wc.recolor(color_func=image_colors)) #为云图去掉坐标轴 plt.axis("off") #画云图,显示 plt.figure() #为背景图去掉坐标轴 plt.axis("off") plt.imshow(bg,cmap=plt.cm.gray) #保存云图 wc.to_file("C:/Users/priesty/Desktop/弹幕数据/2.png")
结果图:
参考文章:https://blog.csdn.net/paxiaochong001/article/details/116937710
https://piqiandong.blog.csdn.net/article/details/79558589 -
【python】B站弹幕数据分析及可视化(爬虫+数据挖掘)
2021-01-12 06:56:13成果展示 项目地址爬取弹幕可以看我之前写的这篇文章:10行代码下载B站弹幕下载代码# download.py'''依赖模块pip install requests'''import reimport requestsurl = input('请输入B站视频链接: ')res = requests....成果展示
项目地址
爬取弹幕
可以看我之前写的这篇文章:10行代码下载B站弹幕
下载代码
# download.py
'''依赖模块
pip install requests
'''
import re
import requests
url = input('请输入B站视频链接: ')
res = requests.get(url)
cid = re.findall(r'"cid":(.*?),', res.text)[-1]
url = f'https://comment.bilibili.com/{cid}.xml'
res = requests.get(url)
with open(f'{cid}.xml', 'wb') as f:
f.write(res.content)
样例输入
样例输出
数据处理
下载弹幕文件51816463.xml后,我们打开看一下:
chat.bilibili.com
51816463
0
3000
0
0
k-v
长颈鹿呢?还是大象呢?(
我也不想的,实在是太大了呀
真是深不可测啊
此处省略很多字
可以看到xml文件中d标签的text部分就是弹幕的文本,而d标签的p属性应该是弹幕的相关参数,共有8个,用逗号分隔。
stime: 弹幕出现时间 (s)
mode: 弹幕类型 (< 7 时为普通弹幕)
size: 字号
color: 文字颜色
date: 发送时间戳
pool: 弹幕池ID
author: 发送者ID
dbid: 数据库记录ID(单调递增)
参数详解:
① stime(float):弹幕出现时间,单位是秒;也就是在几秒出现弹幕。
② mode(int):弹幕类型,有8种;小于8为普通弹幕,8是高级弹幕。
1~3:滚动弹幕
4:底端弹幕
6:顶端弹幕
7:逆向弹幕
8:高级弹幕
③ size(int):字号。
12:非常小
16:特小
18:小
25:中
36:大
45:很大
64:特别大
④ color(int):文字颜色;十进制表示的颜色。
⑤ data(int):弹幕发送时间戳。也就是从基准时间1970-1-1 08:00:00开始到发送时间的秒数。
⑥ pool(int):弹幕池ID。
0:普通池
1:字幕池
2:特殊池(高级弹幕专用)
⑦ author(str):发送者ID,用于"屏蔽此发送者的弹幕"的功能。
⑧ dbid(str):弹幕在数据库中的行ID,用于"历史弹幕"功能。
了解弹幕的参数后,我们就将弹幕信息保存为danmus.csv文件:
# processing.py
import re
with open('51816463.xml', encoding='utf-8') as f:
data = f.read()
comments = re.findall('(.*?)', data)
# print(len(comments)) # 3000
danmus = [','.join(item) for item in comments]
headers = ['stime', 'mode', 'size', 'color', 'date', 'pool', 'author', 'dbid', 'text']
headers = ','.join(headers)
danmus.insert(0, headers)
with open('danmus.csv', 'w', encoding='utf_8_sig') as f:
f.writelines([line+'\n' for line in danmus])
数据分析
词频分析
# wordCloud.py
'''依赖模块
pip install jieba, pyecharts
'''
from pyecharts import options as opts
from pyecharts.charts import WordCloud
import jieba
with open('danmus.csv', encoding='utf-8') as f:
text = " ".join([line.split(',')[-1] for line in f.readlines()])
words = jieba.cut(text)
_dict = {}
for word in words:
if len(word) >= 2:
_dict[word] = _dict.get(word, 0)+1
items = list(_dict.items())
items.sort(key=lambda x: x[1], reverse=True)
c = (
WordCloud()
.add(
"",
items,
word_size_range=[20, 120],
textstyle_opts=opts.TextStyleOpts(font_family="cursive"),
)
.render("wordcloud.html")
)
情感分析
由饼状图可知:3000条弹幕中,积极弹幕超过一半,中立弹幕有百分之三十几。
当然,弹幕调侃内容居中,而且有很多梗,会对情感分析造成很大的障碍,举个栗子:
>>> from snownlp import SnowNLP
>>> s = SnowNLP('阿伟死了')
>>> s.sentiments
0.1373666377744408
"阿伟死了"因带有"死"字,所以被判别为消极情绪。但实际上,它反映的确是积极情绪,形容对看到可爱的事物时的激动心情。
# emotionAnalysis.py
'''依赖模块
pip install snownlp, pyecharts
'''
from snownlp import SnowNLP
from pyecharts import options as opts
from pyecharts.charts import Pie
with open('danmus.csv', encoding='utf-8') as f:
text = [line.split(',')[-1] for line in f.readlines()[1:]]
emotions = {
'positive': 0,
'negative': 0,
'neutral': 0
}
for item in text:
if SnowNLP(item).sentiments > 0.6:
emotions['positive'] += 1
elif SnowNLP(item).sentiments < 0.4:
emotions['negative'] += 1
else:
emotions['neutral'] += 1
print(emotions)
c = (
Pie()
.add("", list(emotions.items()))
.set_colors(["blue", "purple", "orange"])
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"))
.render("emotionAnalysis.html")
)
精彩片段
由折线图可知:第3分钟,第8、第9分钟,还有第13分钟分别是该视频的精彩片段。
# highlights.py
'''依赖模块
pip install snownlp, pyecharts
'''
from pyecharts.commons.utils import JsCode
from pyecharts.charts import Line
from pyecharts.charts import Line, Grid
import pyecharts.options as opts
with open('danmus.csv', encoding='utf-8') as f:
text = [float(line.split(',')[0]) for line in f.readlines()[1:]]
text = sorted([int(item) for item in text])
data = {}
for item in text:
item = int(item/60)
data[item] = data.get(item, 0)+1
x_data = list(data.keys())
y_data = list(data.values())
background_color_js = (
"new echarts.graphic.LinearGradient(0, 0, 0, 1, "
"[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)"
)
area_color_js = (
"new echarts.graphic.LinearGradient(0, 0, 0, 1, "
"[{offset: 0, color: '#eb64fb'}, {offset: 1, color: '#3fbbff0d'}], false)"
)
c = (
Line(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js)))
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="弹幕数量",
y_axis=y_data,
is_smooth=True,
symbol="circle",
symbol_size=6,
linestyle_opts=opts.LineStyleOpts(color="#fff"),
label_opts=opts.LabelOpts(is_show=True, position="top", color="white"),
itemstyle_opts=opts.ItemStyleOpts(
color="red", border_color="#fff", border_width=3
),
tooltip_opts=opts.TooltipOpts(is_show=True),
areastyle_opts=opts.AreaStyleOpts(
color=JsCode(area_color_js), opacity=1),
markpoint_opts=opts.MarkPointOpts(
data=[opts.MarkPointItem(type_="max")])
)
.set_global_opts(
title_opts=opts.TitleOpts(
title="",
pos_bottom="5%",
pos_left="center",
title_textstyle_opts=opts.TextStyleOpts(
color="#fff", font_size=16),
),
xaxis_opts=opts.AxisOpts(
type_="category",
boundary_gap=False,
axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"),
axisline_opts=opts.AxisLineOpts(
linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")
),
axistick_opts=opts.AxisTickOpts(
is_show=True,
length=25,
linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"),
),
splitline_opts=opts.SplitLineOpts(
is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")
)
),
yaxis_opts=opts.AxisOpts(
type_="value",
position="left",
axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"),
axisline_opts=opts.AxisLineOpts(
linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")
),
axistick_opts=opts.AxisTickOpts(
is_show=True,
length=15,
linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"),
),
splitline_opts=opts.SplitLineOpts(
is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")
),
),
legend_opts=opts.LegendOpts(is_show=False),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line")
)
.render("highlights.html")
)
高能时刻
更多时候,我们可能对精彩片段不太关注,而是想知道番剧的名场面出自几分几秒,即高能时刻。
# highEnergyMoment.py
import re
with open('danmus.csv', encoding='utf-8') as f:
danmus = []
for line in f.readlines()[1:]:
time = int(float(line.split(',')[0]))
text = line.split(',')[-1].replace('\n', '')
danmus.append([time, text])
danmus.sort(key=lambda x: x[0])
dict1 = {}
dict2 = {}
control = True
for item in danmus:
if re.search('名场面(:|:)', item[1]):
print(f'{int(item[0]/60)}m{item[0]%60}s {item[1]}')
control = False
break
if '名场面' in item[1]:
minute = int(item[0]/60)
second = item[0] % 60
dict1[minute] = dict1.get(minute, 0)+1
dict2[minute] = dict2.get(minute, 0)+second
else:
pass
if control:
minute= max(dict1, key=dict1.get)
second = round(dict2[minute]/dict1[minute])
print(f'{minute}m{second}s 名场面')
输出:9m29s 名场面:怀中抱妹鲨。我们去视频中看一下,9m29s确实是名场面:
福利情节
字体颜色为黄色,也就是10进制颜色的值为16776960时,就是那种比较污的福利情节,同时为了防止异常,只有当该分钟内出现黄色弹幕的次数≥3时,才说明该分钟内是福利情节,并且输出该分钟内第一次出现黄色弹幕的秒数:
02m15s 吼吼吼
03m30s 什么玩意
06m19s 真的有那么Q弹吗
08m17s 憋死
09m10s 前方万恶之源
10m54s 噢噢噢噢
11m02s 这就是平常心
12m34s 这个我可以
17m19s 因为你是钢筋混凝土直女
18m06s 假面骑士ooo是你吗
19m00s 警察叔叔就是这个人
20m00s 金色传说的说。。。
21m02s 嘿嘿嘿~
# textColor.py
with open('danmus.csv', encoding='utf-8') as f:
danmus = []
for line in f.readlines()[1:]:
time = int(float(line.split(',')[0]))
color = line.split(',')[3]
text = line.split(',')[-1].replace('\n', '')
danmus.append([time, color, text])
danmus.sort(key=lambda x: x[0])
dict1 = {}
dict2 = {}
for item in danmus:
if item[1] == '16776960':
minute = int(item[0]/60)
second = item[0] % 60
dict1[minute] = dict1.get(minute, 0)+1
if dict2.get(minute) == None:
dict2[minute] = f'{minute:0>2}m{second:0>2}s {item[2]}'
else:
pass
for key, value in dict1.items():
if value >= 3:
print(dict2[key])
-
python爬取b站弹幕并进行数据可视化
2019-11-22 19:19:21python爬取b站弹幕并进行数据可视化 1.第一步,爬取b站弹幕 我们随便打开一个b站视频 打开开发者模式,在network下搜索list,可以找到该视频的弹幕文件 打开之后是这个样子的 结构还是比较简单的,我们后续爬取... -
python爬虫实践-B站弹幕分析
2021-10-19 21:03:36系列文章目录 提示:写完文章后,目录可以自动...作为弹幕文化的大本营,必须是B站,B站的大部分有趣都来自于弹幕。 目录 与前两个爬虫实践如出一辙,都是一个主函数作为程序入口,并调用子函数。其它几个def定义的 -
python爬虫教程:爬取Bilibili弹幕过程解析
2020-12-22 09:39:24这篇文章主要介绍了Python爬虫爬取Bilibili弹幕过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 先来思考一个问题,B站一个视频的弹幕最多会有多少? ... -
python源码集锦-爬取bilibili弹幕消息
2021-03-13 11:24:56python源码集锦-爬取bilibili弹幕消息 -
python按日期爬取b站弹幕 2.0版
2021-01-07 14:36:54[分析爬取b站视频弹幕](https://blog.csdn.net/HandsomeFishman/article/details/112171386) 代码 直接附上完整代码: import requests from lxml import etree import pandas as pd from wordcloud import ... -
【Python】b站弹幕系统改版后爬虫方法(bilibili_api)
2021-02-10 21:11:32以前b站弹幕接口是这个: https://api.bilibili.com/x/v1/dm/list.so 返回的是 XML 格式的信息,非常容易解析。 但是,不知道什么时候开始,b站弹幕接口进行了更新,这个接口现在也被废弃了,改成了下面这个: ... -
用python养虫爬弹幕
2022-02-07 20:05:59文章目录前言一、爬虫是什么?二.饲养步骤1. 请求弹幕2.解析弹幕存储弹幕总代码总结 前言 时隔108天,何同学在B站发布了最新的视频,《【何同学】我用108天开了个灯…》。...对于B站弹幕而言,弹幕所在位置是. -
Python应用实战代码-爬取综艺《哈哈哈哈哈》弹幕做情感分析
2021-07-21 14:14:57Python应用实战代码-爬取综艺《哈哈哈哈哈》弹幕做情感分析 -
python爬虫-斗鱼弹幕(asyncore仅供学习参考用)
2021-11-24 11:22:00python编程快速上手(持续更新中…) python爬虫热点项目(Flask ) asyncore 模块 介绍 这个模块为异步socket的服务器客户端通信提供简单的接口。该模块提供了异步socket服务客户端和服务器的基础架构。相比python... -
Python获取B站视频弹幕 简单处理
2021-01-12 06:56:10B站弹幕概述之前看到了网上有人做过一些up的B站弹幕数据可视化,感觉还挺有意思,于是自己就动手做着玩了一下(没有做可视化)。祝福武汉,祝福中国!项目实现(1)获取弹幕数据,我本来想着是获取某一个up的全部视频的... -
这八个步骤,Python让你轻松爬取B站弹幕,网友看了都说666
2021-08-17 20:11:15Python3爬取B站视频弹幕 本文通过8个步骤教你如何使用Python3爬取B站的视频弹幕,快往下看看吧。 需要准备的环境: 一个B站账号,需要先登录,否则不能查看历史弹幕记录 联网的电脑和顺手的浏览器,我用的Chrome ... -
Python获取B站直播间弹幕信息
2020-11-24 05:37:07今天尝试了下获取爬取B站直播间的弹幕,主要分为以下几步:获取弹幕所在的数据信息,通过查看网页源码--Network刷新文件,其中msg中存放着弹幕信息采用requests.post的方式来获取html文件信息,其中传递了url和data... -
AioWebSocket实现python异步接收B站直播弹幕
2022-01-13 08:36:17应用python的AioWebSocket获取B站直播弹幕 -
python3爬取B站视频历史弹幕
2021-07-29 17:51:50python爬取B站视频历史弹幕演示 演示 1.运行程序,输入Bvid和爬取日期。 2.程序运行完成后会在当前文件夹下生成一个csv格式文件。 -
《用python 玩转数据》项目——B站弹幕数据分析
2020-12-11 02:01:37本项目,就是对B站弹幕数据进行分析。选取分析的对象是B站上点播量过1.4亿的一部剧《Re:从零开始的异世界生活》。2.算法分两部分:第一部分:2.1在《Re:从零开始的异世界生活》的首页面,找到共25集的所有对应播放... -
Python爬虫自动化爬取b站实时弹幕实例方法
2021-03-05 18:31:31免费资源网,https://freexyz.cn/最近央视新闻记者王冰冰以清除可爱和...本文以王冰冰视频弹幕为例,向大家介绍Python爬虫实现自动化爬取b站实时弹幕的过程。1、导入需要的库import jieba # 分词from wordcloud impo... -
利用python爬取b站弹幕和统计(附保存)
2020-07-17 22:24:50我拿起手机一看已经中午12点了,b站的百妖谱应该完结更新了,再点开微信一看,我的朋友发来了消息,告诉我说今天的百妖谱好催泪啊,不过我没有看过,但是又没有时间去看,就只好把百妖谱的弹幕爬取出来,好让我们能... -
Python爬虫入门教程05:B站视频弹幕的爬取
2021-01-25 16:55:08Python爬虫入门教程01:豆瓣Top电影爬取 Python爬虫入门教程02:小说爬取 Python爬虫入门教程03:二手房数据爬取 Python爬虫入门教程04:招聘信息爬取 PS:如有需要 Python学习资料 以及 解答 的小伙伴可以加点击... -
python 爬取B站弹幕显示乱码,各位大佬麻烦帮我康康
2021-03-20 00:30:30求教emmmmmm <p>1、源网页查看显示乱码(改过网页编码方式也不行) <p>2、代码输出也改过编码方式,也是乱码。 <p><img alt="" height="597" src=...