Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

时间:2023-03-09 17:04:57
Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

一 . Java爬取B站弹幕

弹幕的存储位置

Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

如何通过B站视频AV号找到弹幕对应的xml文件号

首先爬取视频网页,将对应视频网页源码获得

Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

就可以找到该视频的av号aid=8678034

还有弹幕序号,cid=14295428

弹幕存放位置为  http://comment.bilibili.com/14295428.xml

 import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class getBiliBiliBofqi {
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
public static void getBofqi(String aid) throws Exception {
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://www.bilibili.com/video/av" + aid + "/");
CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String en = EntityUtils.toString(httpEntity);
//"cid=16496518&aid=9979006&pre_ad="
String con = "cid=(.*)?&aid=";
Pattern ah = Pattern.compile(con);
Matcher mr = ah.matcher(en);
while (mr.find()) {
String id = mr.group();
// 解析弹幕xml文件
String newUrl = id.replace("cid=", "");
String x = newUrl.replace("&aid=", "");
if(!isInteger(x)){
return ;
}
URL url = new URL( "http://comment.bilibili.com/"+x+".xml" );
HttpGet httpGet1 = new HttpGet("http://comment.bilibili.com/"+x+".xml");
CloseableHttpResponse httpResponse1 = closeableHttpClient.execute(httpGet1) ;
HttpEntity httpEntity1 = httpResponse1.getEntity() ;
String en1 = EntityUtils.toString(httpEntity1,"utf-8") ; String c = "\">(.*?)<";
Pattern a = Pattern.compile(c);
Matcher m = a.matcher(en1);
RandomAccessFile randomAccessFile = new RandomAccessFile("E:\\dan_"+x+".txt", "rw");
while (m.find()) {
String speak = m.group().replace("\">", "");
speak = speak.replace("<", ""); // 存储弹幕
long len = randomAccessFile.length();
randomAccessFile.seek(len);
randomAccessFile.write(speak.getBytes());
randomAccessFile.write("\r\n".getBytes());
System.out.println(speak);
}
randomAccessFile.write("\r\n".getBytes());
randomAccessFile.close();
}
}
public static void main(String[] args) throws Exception {
getBofqi("16772795");
getBofqi("8542373");
getBofqi("5112921");
getBofqi("1747345");
getBofqi("2648921");
getBofqi("2333333");
getBofqi("3771373");
getBofqi("17224371");
}
}

爬取的弹幕文件 :

Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

运行结果:

Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

二 . Python云图Wordcloud生成弹幕词云

1      github:https://github.com/amueller/word_cloud
官方地址:https://amueller.github.io/word_cloud/

Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云

# coding: utf-8
import jieba
from scipy.misc import imread # 这是一个处理图像的函数
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import matplotlib.pyplot as plt back_color = imread('02.jpg') # 解析该图片 wc = WordCloud(background_color='white', # 背景颜色
max_words=500, # 最大词数
#mask=back_color, # 以该参数值作图绘制词云,这个参数不为空时,width和height会被忽略
max_font_size=100, # 显示字体的最大值
stopwords=STOPWORDS.add('fa'), # 使用内置的屏蔽词,再添加'苟利国'
font_path="C:/Windows/Fonts/STFANGSO.ttf", # 解决显示口字型乱码问题,可进入C:/Windows/Fonts/目录更换字体
random_state=42, # 为每个词返回一个PIL颜色
width=1000, # 图片的宽
height=860 #图片的长
)
# WordCloud各含义参数请点击 wordcloud参数 # 打开词源的文本文件
text = open('dan_6051409.txt').read() # 该函数的作用就是把屏蔽词去掉,使用这个函数就不用在WordCloud参数中添加stopwords参数了
# 把你需要屏蔽的词全部放入一个stopwords文本文件里即可
def stop_words(texts):
words_list = []
word_generator = jieba.cut(texts, cut_all=False) # 返回的是一个迭代器
with open('stopwords.txt') as f:
str_text = f.read()
unicode_text = unicode(str_text, 'utf-8') # 把str格式转成unicode格式
f.close() # stopwords文本中词的格式是'一词一行'
for word in word_generator:
if word.strip() not in unicode_text:
words_list.append(word)
return ' '.join(words_list) # 注意是空格 text = stop_words(text) wc.generate(text)
# 基于彩色图像生成相应彩色
image_colors = ImageColorGenerator(back_color)
# 显示图片
plt.imshow(wc)
# 关闭坐标轴
plt.axis('off')
# 绘制词云
plt.figure()
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis('off')
# 保存图片
wc.to_file('1.png')

word_cloud 生成词云有两个方法。from text 和 from frequencies 。

即文本生成和频率生成,每一个都有对应的函数可以使用

 generate(text)      Generate wordcloud from text.
generate_from_text(text) Generate wordcloud from text.
generate_from_frequencies Create a word_cloud from words and frequencies.
fit_words Create a word_cloud from words and frequencies.

wordcloud包的基本用法

 class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2,
ranks_only=None, prefer_horizontal=0.9,mask=None, scale=1, color_func=None,
max_words=200, min_font_size=4, stopwords=None, random_state=None,background_color='black',
max_font_size=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None,
collocations=True,colormap=None, normalize_plurals=True)
  1. font_path : string //字体路径,需要展现什么字体就把该字体路径+后缀名写上,如:font_path = '黑体.ttf'
  2. width : int (default=400) //输出的画布宽度,默认为400像素
  3. height : int (default=200) //输出的画布高度,默认为200像素
  4. prefer_horizontal : float (default=0.90) //词语水平方向排版出现的频率,默认 0.9 (所以词语垂直方向排版出现频率为 0.1 )
  5. mask : nd-array or None (default=None) //如果参数为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代。
  6. 除全白(#FFFFFF)的部分将不会绘制,其余部分会用于绘制词云。如:bg_pic = imread('读取一张图片.png'),
  7. 背景图片的画布一定要设置为白色(#FFFFFF),然后显示的形状为不是白色的其他颜色。可以用ps工具将自己要显示的形状复制到一个纯白色的画布上再保存,就ok了。
  8. scale : float (default=1) //按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍。
  9. min_font_size : int (default=4) //显示的最小的字体大小
  10. font_step : int (default=1) //字体步长,如果步长大于1,会加快运算但是可能导致结果出现较大的误差。
  11. max_words : number (default=200) //要显示的词的最大个数
  12. stopwords : set of strings or None //设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS
  13. background_color : color value (default=”black”) //背景颜色,如background_color='white',背景颜色为白色。
  14. max_font_size : int or None (default=None) //显示的最大的字体大小
  15. mode : string (default=”RGB”) //当参数为“RGBA”并且background_color不为空时,背景为透明。
  16. relative_scaling : float (default=.5) //词频和字体大小的关联性
  17. color_func : callable, default=None //生成新颜色的函数,如果为空,则使用 self.color_func
  18. regexp : string or None (optional) //使用正则表达式分隔输入的文本
  19. collocations : bool, default=True //是否包括两个词的搭配
  20. colormap : string or matplotlib colormap, default=”viridis” //给每个单词随机分配颜色,若指定color_func,则忽略该方法。
  21. fit_words(frequencies) //根据词频生成词云【frequencies,为字典类型】
  22. generate(text) //根据文本生成词云
  23. generate_from_frequencies(frequencies[, ...]) //根据词频生成词云
  24. generate_from_text(text) //根据文本生成词云
  25. process_text(text) //将长文本分词并去除屏蔽词(此处指英语,中文分词还是需要自己用别的库先行实现,使用上面的 fit_words(frequencies) )
  26. recolor([random_state, color_func, colormap]) //对现有输出重新着色。重新上色会比重新生成整个词云快很多。
  27. to_array() //转化为 numpy array
  28. to_file(filename) //输出到文件