【Python爬虫】CSDN热榜文章热门词汇分析( 二 )


上述代码使用for循环获取全部文章信息,其中i表示页数 。
使用sys库获取当前py文件所在的目录,以防代码在不同电脑上运行,路径不同存储读取出现问题
if __name__ == "__main__":...# 当前py文件所在的目录bath_path = sys.path[0]with open(f"{bath_path}\\file\csdn热榜分析.csv", "w", newline="", encoding="utf-8-sig") as file:writer = csv.writer(file)writer.writerow(["标题", "标签","作者","评论数" ,"收藏量","浏览量", "热度值", "文章链接"])writer.writerows(hot_data_list)...
分词
Jieba是一个流行的中文分词库,它能够将中文文本切分成词语,并对每个词语进行词性标注 。中文分词是自然语言处理的重要步骤之一,它对于文本挖掘、信息检索、情感分析等任务具有重要意义 。
接下来,我们将使用jieba库对标题和标签进行分词处理,以便后续的数据分析 。
import jieba# 读取标题和标签文本with open('csdn热榜标签.txt', 'r') as file:titles = file.readlines()with open('csdn热榜标签.txt', 'r') as file:tags = file.readlines()# 分词处理title_words = [jieba.lcut(title.strip()) for title in titles]tag_words = [jieba.lcut(tag.strip()) for tag in tags]# 查看分词结果print(title_words[:5])print(tag_words[:5])
在上述代码中,我们使用jieba库对标题和标签进行分词处理 。首先,我们使用jieba.lcut()函数对每个标题和标签进行分词,并将结果存储在列表中 。分词结果是一个列表的列表,每个子列表表示一个标题或标签的分词结果 。
柱形图分词统计

【Python爬虫】CSDN热榜文章热门词汇分析

文章插图
构造字典,逐一遍历分词结果中的中文单词进行处理,并用字典计数,然后转为列表进行排序(代码为标题部分示例) 。
counts = {}# 构造字典,计数for title_word in title_words:for word in title_word:if len(word) == 1:continueelse:counts[word] = counts.get(word, 0) + 1items = list(counts.items())# 转换,排序items.sort(key=lambda x: x[1], reverse=True)
绘制柱形图
使用库对标题和标签分词数据进行可视化,这里截取前20的热词 。(代码为标题部分示例)
from matplotlib import pyplot as pltnewitems = items[0:20:1] # 截取前20tu = dict(newitems)# 定义 x和 y的空列表,用于分别存放tu字典的键和值x = []y = []# 列车键和分别追加到x和y列表for k in tu:x.append(k)y.append(tu[k])plt.title("csdn热榜标签词汇统计", fontsize=25)# 打印标题plt.xlabel("热门词汇")# x标签plt.ylabel("词频")# y标签plt.xticks(rotation=45, fontsize=10)# 输出图表中间的文字各种格式的定义for a, b in zip(x, y):plt.text(a, b, "%.0f" % b, ha="center", va="bottom", fontsize=12, )plt.bar(x, y, label="频率") # 图示plt.legend()plt.show()# 图表展示
运行结果:
中文显示出现问题,解决办法如下:
# 支持中文plt.rcParams["font.sans-serif"] = ["SimHei"]# 用来正常显示中文标签
运行结果:
柱形图完成o( ̄▽ ̄)ブ
?? 制作词云
词云是一种可视化工具,可以直观地显示文本数据中词语的重要程度 。下面我们使用库制作标题和标签的词云图 。
# 分词处理title_words = [jieba.lcut(title.strip()) for title in titles][0]tag_words = [jieba.lcut(tag.strip()) for tag in tags][0]title_words_str = ' '.join(title_words) # 连接成字符串tag_words_str = ' '.join(tag_words) # 连接成字符串stopwords = ["[", "]", "【", "】",'(',')', '(', ')', '|', '/', ] # 去掉不需要显示的词words_img = wordcloud.WordCloud(font_path="msyh.ttc",width = 1000,height = 700,background_color='white',max_words=100,stopwords=stopwords)# msyh.ttc电脑本地字体,写可以写成绝对路径words_img.generate(title_words_str)# 加载标题词云文本words_img.to_file(r"..\file\标题词云.png") # 保存词云文件words_img.generate(tag_words_str)# 加载标签词云文本words_img.to_file(r"..\file\标签词云.png") # 保存词云文件