Python分析人民日报关于台湾的报道

【项目背景】

《人民日报》数据挖掘,时间:1949.10.1-2023.12.31 标题含有"台湾"的报道

需要以下内容

1、标题,即上述时间段的报道标题和相应的报道时间、版面

2、包含标题、时间、版面的所有报道内容

3、报道的年份和数量的趋势图

4、词频图表,1949.10.1-1978.12.31,1979.1.1-2016.5.20,2016.5.21-2023.12.31,三个时间段的人民日报标题的词频图三张,词频图表需显示出高频词是什么,分别占比多少;

5.需添加数据挖掘过程简要说明:用了什么python 哪一版进行数据挖掘;通过python 或其他软件统计词频,因什么原因剔除了什么,得到什么结果。

基本原理

通过编写爬虫程序抓取《人民日报》从1949年10月1日到2023年12月31日的新闻数据,再对抓取到的新闻数据进行词频分析,绘制报道数量和年份趋势图,以及三个时间段的人民日报标题的词频图,从而获取所需的数据。

核心代码

import pandas as pd
from bs4 import BeautifulSoup
import requests
import matplotlib.pyplot as plt
from collections import Counter

# 设置所需参数
url = 'http://paper.people.com.cn/rmrb/html/2018-01/01/content_180019891.htm'
start_date = '1949-10-01'
end_date = '2023-12-31'
url_pattern = 'http://paper.people.com.cn/rmrb/{}/{}/index.shtml'

# 定义爬虫函数
def get_news_data(url_pattern, start_date, end_date):
    news_data = []
    for year in range(start_date[0], end_date[0] + 1):
        year_str = '-'.join(str(year))
        for month in range(1, 13):
            month_str = '-'.join(str(year), str(month).zfill(2))
            if year == end_date[0] and month > end_date[1]:
                break
            if month < 10:
                month_str = month_str[0:2] + '.0' + month_str[2:]
            url = url_pattern.format(year_str, month_str)
            print(url)
            page = requests.get(url)
            soup = BeautifulSoup(page.text, 'html.parser')
            titles = soup.find_all('title')[0:50]
            for title in titles:
                news_data.append({
                    'title': title.get_text(), 
                    'time': title.parent.parent.find('span', 'date').get_text(),
                    'page': title.parent.parent.parent.find('span', 'page').get_text()
                })
    df = pd.DataFrame(news_data)
    df['date'] = pd.to_datetime(df['date'])
    df['year'] = df['date'].dt.year
    df['month'] = df['date'].dt.month
    return df

# 绘制报道数量和年份趋势图
def plot_year_trend(df):
    df.groupby('year')['date'].count().plot()
    plt.title('报道数量趋势图')
    plt.show()

# 词频分析
def count_word(df):
    words_1949_1978 = Counter(df[(df.year < 1979) & (df.year >= 1949)].title.apply(lambda x: str(x).split()))
    words_1979_2016 = Counter(df[(df.year >= 1979) & (df.year < 2017)].title.apply(lambda x: str(x).split()))
    words_2017_2023 = Counter(df[(df.year >= 2017) & (df.year <= 2023)].title.apply(lambda x: str(x).split()))
    top_words_1949_1978 = [word[0] for word in words_1949_1978.most_common(20)]
    top_words_1979_2016 = [word[0] for word in words_1979_2016.most_common(20)]
    top_words_2017_2023 = [word[0] for word in words_2017_2023.most_common(20)]
    top_words = top_words_1949_1978 + top_words_1979_2016 + top_words_2017_2023
    print('高频词')
    for index, word in enumerate(top_words, start=1):
        print(f'{index}. {word} {words_1949_1978.get(word, 0) + words_1979_2016.get(word, 0) + words_2017_2023.get(word, 0)}')

# 运行程序
df = get_news_data(url_pattern, start_date, end_date)
plot_year_trend(df)
count_word(df)

注意事项

  • 使用的爬虫框架是 Python requests 和 BeautifulSoup,需要注意 User- Agent 的切换以防止被反爬虫机制识别
  • 由于请求速度的问题,需要注意数据的抓取速度,需要分批抓取,防止服务器压力过大
  • 在词频分析的过程中,需要注意去除非汉字字符,因为人民日报中也包含英文、数字等非汉字字符,这些字符对于词频分析没有帮助,反而会影响结果的准确性。可以通过正则表达式等方式去除这些非汉字字符。
  • 在绘制词频图时,由于数据量较大,需要使用对数坐标轴或者将数据聚合到更高的层级(如每周、每月)以避免数据过于稀疏难以观察。
  • 由于人民日报的版面众多,本示例代码只抓取了头版的标题和时间,如果需要抓取更多版面的信息,可以修改代码中的 URL 拼接方式以及解析 HTML 的方式。
  • 由于人民日报的报道量巨大,本示例代码只抓取了部分数据进行分析,如果需要更全面的数据分析,可以考虑使用分布式爬虫或者并行计算等技术提高数据抓取和分析的效率。
  • 在数据挖掘过程中,还需要注意数据的质量和完整性,如缺失值、重复值等问题,需要进行适当的数据清洗和处理。同时,还需要遵守相关法律法规和伦理规范,确保数据使用的合法性和正当性。

civilpy:Python分析无人驾驶汽车在桂林市文旅行业推广的问卷0 赞同 · 0 评论文章​编辑

civilpy:Python数据分析及可视化实例目录940 赞同 · 36 评论文章​编辑

civilpy:Python通过某上市企业经营业绩预测股价走势0 赞同 · 0 评论文章​编辑

civilpy:Python实时追踪关键点组成人体模型0 赞同 · 0 评论文章​编辑

相关推荐
鸽芷咕19 分钟前
【Python报错已解决】ModuleNotFoundError: No module named ‘tensorflow‘
python·机器学习·tensorflow·bug·neo4j
李元豪21 分钟前
python 自动化 win11 编程 实现 一键 启动多个软件,QQ浏览器,snipaste,pycharm软件
python·pycharm·自动化
痛&快乐着22 分钟前
python-在PyCharm中使用PyQt5
python·qt·pycharm
fydw_71528 分钟前
PyTorch 激活函数及非线性变换详解
人工智能·pytorch·python
Rverdoser29 分钟前
在 PyCharm 中配置 Anaconda 环境
ide·python·pycharm
IT小辉同学1 小时前
用 Pygame 实现一个乒乓球游戏
python·游戏·pygame
虚假程序设计1 小时前
pythonnet python图像 C# .NET图像 互转
开发语言·人工智能·python·opencv·c#·.net
测试老哥2 小时前
功能测试干了三年,快要废了。。。
自动化测试·软件测试·python·功能测试·面试·职场和发展·压力测试
爱吃油淋鸡的莫何2 小时前
Conda新建python虚拟环境问题
开发语言·python·conda
闲人编程2 小时前
Python实现日志采集功能
开发语言·python·fluentd·filebeat·日志采集