突发奇想想对自己的2024进行分析。
于是决定把豆瓣广播变成词云,学习一下词云的制作方法
分为几步:
1.获取数据,爬取2024的豆瓣广播
#引入requests和BeautifulSoup
import requests
from bs4 import BeautifulSoup
base_url="我的豆瓣主页网址/p?="
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
'Cookie':你自己的Cookie
}
#从url中获得html
def fetch_html(url, headers):
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an HTTPError for bad responses
return response.text
#获取广播的内容和发表时间
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
status_items = soup.find_all('div', class_='status-item')
data = []
for item in status_items:
content_tag = item.find('blockquote', class_='quote-clamp')
if content_tag:
content_p = content_tag.find('p')
#获取内容和发表日期
content = content_p.get_text(strip=True) if content_p else ''
created_at_tag = item.find('span', class_='created_at')
created_at = created_at_tag.get('title') if created_at_tag else ''
date_format = "%Y-%m-%d %H:%M:%S"
try:
#转换日期的格式
created_at = datetime.strptime(created_at, date_format)
except ValueError:
print(f"无法解析日期字符串: {created_at}")
data.append({
"created_at": created_at,
"content": content
})
return data
#把获得的内容放入一个csv文件
def save_to_csv(data, filename):
# 检查文件是否存在
file_exists = os.path.isfile(filename)
#打开文件,a代表追加,而不是直接覆盖
with open(filename, 'a', newline='', encoding='utf-8') as csvfile:
fieldnames = ['created_at', 'content']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# 如果文件不存在,创建文件并写入表头
if not file_exists:
writer.writeheader()
# 写入数据
writer.writerows(data)
print(f"Data has been {'appended to' if file_exists else 'written to'} {filename}")
#根据年获取内容
def fetch_page_by_year(base_url, year, headers):
# 我们需要遍历多个页面来查找2024年的数据
# 需要根据需要设置起始页面,可能需要写个方法找出起始页面,这里先设定成1了
page = 1
end=False
while not end:
# 获取 HTML 内容
url = base_url + str(page)
html_content = fetch_html(url, headers)
# 解析 HTML 内容
data = parse_html(html_content)
# 筛选2024年的数据
data_2024 = []
for item in data:
#获取时间
item_date = item.get('created_at')
print(item_date)
if item_date:
print(item_date.year)
#如果时间不等于规定时间了,暂停循环
if item_date.year!=year:
end=True
else:
data_2024.append(item)
page=page+1
# 保存2024年的数据到 CSV 文件
save_to_csv(data_2024, f'douban_statuses_{year}.csv')
然后得到了这样一个csv文件:
created_at,content 2024-01-06 23:39:10,一个广播内容。 2024-01-06 22:46:42,另外一个广播内容。 2024-11-17 02:53:22, 2024-11-15 14:28:06,又一个广播内容
会出现内容是空白的项目,这是因为这里是我的想看电影
2.清洗数据,去掉内容是空白的地方
#引入库
import pandas as pd
import numpy as np
# 读取CSV文件:
df=pd.read_csv("douban_statuses_2024_use.csv")
# 去除content列为空的项目
df.dropna(subset=['content'])
#还可以根据需要去掉HTML标签、把日期不正确的改正确,这里没有这个问题,先省去
3.生成词云图
#引入库
import numpy as np
import jieba.analyse
from PIL import Image
from wordcloud import WordCloud
#把所有广播的内容连成一个
title=''.join([str(c) for c in df['content']])
# 输入停用词,停用词就是“的”,“了”等需要去掉的词语
#stopwords.txt文件是我在网上搜索的停用词复制的
jieba.analyse.set_stop_words('stopwords.txt')
text = jieba.analyse.extract_tags(title, topK=50, withWeight=True) # 去除停用词+词频分析
word_dict = {} # 转化为字典形式以便做词云图
for i in text:
word_dict[i[0]] = i[1]
#插入一个背景图片,插入了一下本人最喜欢的照片,不过需要注意要把背景图片的背景改成白色,之前的Png的背景是透明的,显现不出来
background_image_path='img.png'
background_image = np.array(Image.open(background_image_path))
#生成词云图
wc = WordCloud(font_path="msyh.ttc",
mask=background_image,
background_color='white',
max_words=100).fit_words(word_dict)
#plt显示
plt.figure(figsize=(12, 8))
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()