Python实例题:Python获取小说数据并分析
目录
Python实例题
题目
实现思路
代码实现
代码解释
get_novel_text 函数:
clean_text 函数:
analyze_word_frequency 函数:
analyze_chapter_length 函数:
visualize_word_frequency 函数:
visualize_chapter_lengths 函数:
主程序:
运行思路
注意事项
Python实例题
题目
Python获取小说数据并分析
实现思路
- 数据获取:使用
requests
库从网络上下载小说文本,使用BeautifulSoup
库解析 HTML 页面提取小说内容。 - 数据清洗:去除小说文本中的特殊字符、空格等无用信息。
- 数据分析:统计小说的词汇频率、章节长度等信息。
- 数据可视化:使用
matplotlib
库将分析结果进行可视化展示。
代码实现
import requests
from bs4 import BeautifulSoup
import re
import collections
import matplotlib.pyplot as pltdef get_novel_text(url):"""从指定 URL 获取小说文本:param url: 小说页面的 URL:return: 小说文本"""try:response = requests.get(url)response.raise_for_status()response.encoding = response.apparent_encodingsoup = BeautifulSoup(response.text, 'html.parser')# 假设小说内容在 <p> 标签中,实际需根据网页结构调整paragraphs = soup.find_all('p')text = ''.join([p.get_text() for p in paragraphs])return textexcept requests.RequestException as e:print(f"请求出错: {e}")return Nonedef clean_text(text):"""清洗小说文本,去除特殊字符和多余空格:param text: 原始小说文本:return: 清洗后的文本"""text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', ' ', text)text = re.sub(r'\s+', ' ', text).strip()return textdef analyze_word_frequency(text):"""分析小说中词汇的频率:param text: 小说文本:return: 词汇频率统计结果"""words = text.split()word_counts = collections.Counter(words)return word_countsdef analyze_chapter_length(text, chapter_pattern):"""分析小说各章节的长度:param text: 小说文本:param chapter_pattern: 章节标题的正则表达式模式:return: 各章节的长度列表"""chapters = re.split(chapter_pattern, text)chapter_lengths = [len(chapter) for chapter in chapters if chapter.strip()]return chapter_lengthsdef visualize_word_frequency(word_counts, top_n=10):"""可视化词汇频率统计结果:param word_counts: 词汇频率统计结果:param top_n: 显示前 n 个高频词汇"""top_words = word_counts.most_common(top_n)words, counts = zip(*top_words)plt.figure(figsize=(10, 6))plt.bar(words, counts)plt.xlabel('词汇')plt.ylabel('出现次数')plt.title(f'小说中前 {top_n} 个高频词汇')plt.xticks(rotation=45)plt.show()def visualize_chapter_lengths(chapter_lengths):"""可视化各章节的长度:param chapter_lengths: 各章节的长度列表"""plt.figure(figsize=(10, 6))plt.plot(chapter_lengths)plt.xlabel('章节序号')plt.ylabel('章节长度')plt.title('小说各章节长度分布')plt.show()if __name__ == "__main__":# 示例小说 URL,需替换为实际的小说页面 URLnovel_url = 'https://example.com/novel'# 获取小说文本novel_text = get_novel_text(novel_url)if novel_text:# 清洗文本cleaned_text = clean_text(novel_text)# 分析词汇频率word_freq = analyze_word_frequency(cleaned_text)# 分析章节长度,假设章节标题以“第 X 章”开头chapter_pattern = r'第[一二三四五六七八九十百千]+章'chapter_lengths = analyze_chapter_length(cleaned_text, chapter_pattern)# 可视化词汇频率visualize_word_frequency(word_freq)# 可视化章节长度visualize_chapter_lengths(chapter_lengths)
代码解释
-
get_novel_text
函数:- 使用
requests
库发送 HTTP 请求获取小说页面的 HTML 内容。 - 使用
BeautifulSoup
库解析 HTML 页面,提取小说内容。
- 使用
-
clean_text
函数:- 使用正则表达式去除小说文本中的特殊字符和多余空格。
-
analyze_word_frequency
函数:- 将文本按空格分割成词汇列表。
- 使用
collections.Counter
统计每个词汇的出现频率。
-
analyze_chapter_length
函数:- 使用正则表达式根据章节标题分割小说文本。
- 计算每个章节的长度。
-
visualize_word_frequency
函数:- 选取前
n
个高频词汇。 - 使用
matplotlib
绘制柱状图展示词汇频率。
- 选取前
-
visualize_chapter_lengths
函数:- 使用
matplotlib
绘制折线图展示各章节的长度分布。
- 使用
-
主程序:
- 定义小说页面的 URL,调用
get_novel_text
函数获取小说文本。 - 对文本进行清洗、词汇频率分析和章节长度分析。
- 可视化分析结果。
- 定义小说页面的 URL,调用
运行思路
- 安装依赖库:确保已经安装了
requests
、beautifulsoup4
和matplotlib
库,可以使用以下命令进行安装:
pip install requests beautifulsoup4 matplotlib
- 替换 URL:将
novel_url
替换为实际的小说页面 URL。 - 运行脚本:将上述代码保存为
novel_data_analysis.py
文件,在终端中运行:
python novel_data_analysis.py
- 查看结果:脚本运行后,会弹出两个窗口分别展示词汇频率和章节长度的可视化结果。
注意事项
- 网站反爬机制:不同网站有不同的反爬策略,可能需要添加请求头、使用代理等方法绕过反爬机制。
- 正则表达式调整:章节标题的正则表达式模式需要根据小说的实际格式进行调整。
- 数据质量:如果小说页面的 HTML 结构复杂,可能需要更复杂的解析逻辑来准确提取小说内容。