📰 用 Python + Word2Vec 自动抓取人民日报内容并生成词频分析与词云
XiaoYu
说明
人民日报是中国最具代表性的官方媒体之一,其每日内容涵盖时政、经济、社会、文化等多个方面,非常适合作为中文语料的分析对象。
这篇文章:自动抓取人民日报某日某版块的所有文章,使用 jieba 分词、Word2Vec 训练词向量,并可视化生成高频词统计和词云图。便于了解当天报道中出现较多的内容。(做交易或者看新闻趋势亦有助益)
整个流程只需要一段不到 200 行的 Python 脚本。
步骤概览
- 抓取文章列表与正文:使用 Playwright 爬取人民日报网页版的某个版块,提取所有文章链接和内容。
- 分词与 Word2Vec 建模:用 jieba 进行中文分词,用 gensim 的 Word2Vec 训练词向量。
- 词频统计与词云生成:统计高频词,并用 matplotlib 和 WordCloud 生成图表。
- 主程序调用上述功能。
代码块
抓取文章链接与正文
人民日报网页版采用静态 HTML + JS 渲染结构,因此我们用 playwright 来模拟浏览器加载页面,确保能拿到所有链接。
python
def get_article_links(date_str: str, node: str):
base_url = f"https://paper.people.com.cn/rmrb/pc/layout/{date_str.replace('-', '/')}/node_{node}.html"
print(f"📰 正在加载页面:{base_url}")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(base_url, timeout=60000)
page.wait_for_load_state("networkidle")
links = page.eval_on_selector_all("a", "elements => elements.map(a => a.href)")
article_links = [link for link in links if "content_" in link]
browser.close()
return list(set(article_links))
对于每篇文章,再抓取标题与正文段落:
python
def fetch_article(url: str):
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(url, timeout=60000)
page.wait_for_load_state("networkidle")
title = page.eval_on_selector("h1", "el => el.innerText") if page.query_selector("h1") else "未找到标题"
paragraphs = page.eval_on_selector_all("body p", "els => els.map(e => e.innerText)")
content = "\n".join(paragraphs)
browser.close()
return {"title": title, "content": content}
分词与 Word2Vec 建模
我们用 jieba 分词,去除纯数字和长度为 1 的词,然后用 gensim 的 Word2Vec 模型来训练向量。
python
def train_word2vec(text: str, vector_size=100, window=5, min_count=2):
sentences = [list(jieba.cut(line)) for line in text.split("\n") if line.strip()]
model = Word2Vec(sentences, vector_size=vector_size, window=window, min_count=min_count)
return model, sentences
接着统计词频,提取 Top 30 高频词:
python
def count_word_freq_from_sentences(sentences, top_k=30):
all_words = [w for sent in sentences for w in sent if len(w.strip()) > 1 and not re.match(r'\d+', w)]
counter = Counter(all_words)
return counter.most_common(top_k)
词频与词云可视化
使用 matplotlib 绘制柱状图:
python
def plot_word_freq(freq_data, title):
words, counts = zip(*freq_data)
plt.figure(figsize=(10, 6))
plt.bar(words, counts)
plt.xticks(rotation=45)
plt.title(f"{title} 高频词统计")
plt.tight_layout()
plt.show()
使用 WordCloud 生成中文词云(记得指定中文字体):
python
def generate_wordcloud(freq_data, title):
wc = WordCloud(font_path="msyh.ttc", background_color="white", width=800, height=600)
wc.generate_from_frequencies(dict(freq_data))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.title(f"{title} 词云图")
plt.show()
测试
提醒
date_str: 这是日期,注意格式!
node: 这是版面序号,例如主板 01 02 以及我们可能关注的经济版(人民日报的内容版号不固定)
python
# 这里把今天的日期输入进去 运行主程序
date_str = "202510/15"
node = "01"



完整代码
python
import re
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from collections import Counter
from playwright.sync_api import sync_playwright
from gensim.models import Word2Vec
import jieba
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# =========================
# 1️⃣ 抓取文章列表与正文(同你原代码)
# =========================
def get_article_links(date_str: str, node: str):
base_url = f"https://paper.people.com.cn/rmrb/pc/layout/{date_str.replace('-', '/')}/node_{node}.html"
print(f"📰 正在加载页面:{base_url}")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(base_url, timeout=60000)
page.wait_for_load_state("networkidle")
links = page.eval_on_selector_all("a", "elements => elements.map(a => a.href)")
article_links = [link for link in links if "content_" in link]
browser.close()
print(f"✅ 共发现 {len(article_links)} 篇文章链接")
return list(set(article_links))
def fetch_article(url: str):
print(f"🔍 抓取文章:{url}")
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(url, timeout=60000)
page.wait_for_load_state("networkidle")
title = page.eval_on_selector("h1", "el => el.innerText") if page.query_selector("h1") else "未找到标题"
paragraphs = page.eval_on_selector_all("body p", "els => els.map(e => e.innerText)")
content = "\n".join(paragraphs)
browser.close()
return {"title": title, "content": content}
# =========================
# 2️⃣ Word2Vec 分析
# =========================
def train_word2vec(text: str, vector_size=100, window=5, min_count=2):
# 先分词
sentences = [list(jieba.cut(line)) for line in text.split("\n") if line.strip()]
# 训练模型
model = Word2Vec(sentences, vector_size=vector_size, window=window, min_count=min_count)
return model, sentences
def count_word_freq_from_sentences(sentences, top_k=30):
all_words = [w for sent in sentences for w in sent if len(w.strip()) > 1 and not re.match(r'\d+', w)]
counter = Counter(all_words)
return counter.most_common(top_k)
# =========================
# 3️⃣ 可视化输出
# =========================
def plot_word_freq(freq_data, title):
if not freq_data:
print("⚠️ 没有可用的词频数据,无法绘图")
return
words, counts = zip(*freq_data)
plt.figure(figsize=(10, 6))
plt.bar(words, counts)
plt.xticks(rotation=45)
plt.title(f"{title} 高频词统计")
plt.tight_layout()
plt.show()
def generate_wordcloud(freq_data, title):
if not freq_data:
print("⚠️ 没有可用的词频数据,无法生成词云")
return
wc = WordCloud(font_path="msyh.ttc", background_color="white", width=800, height=600)
wc.generate_from_frequencies(dict(freq_data))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.title(f"{title} 词云图")
plt.show()
# =========================
# 4️⃣ 主程序
# =========================
if __name__ == "__main__":
date_str = "202510/15"
node = "01"
links = get_article_links(date_str, node)
all_text = ""
for i, link in enumerate(links, 1):
print(f"\n📖 正在抓取第 {i}/{len(links)} 篇:{link}")
article = fetch_article(link)
print(f"标题:{article['title']}")
all_text += article["content"] + "\n"
print(f"\n✅ 【{date_str}】 第 【{node}】 版所有文章已抓取完毕,开始 Word2Vec 训练...\n")
model, sentences = train_word2vec(all_text)
freq = count_word_freq_from_sentences(sentences, top_k=30)
for w, c in freq:
print(f"{w}: {c}")
# plot_word_freq(freq, f"人民日报{date_str}第{node}版")
# generate_wordcloud(freq, f"人民日报{date_str}第{node}版")
补充说明:词频统计与词云不依赖 Word2Vec,词向量训练用于探索词语关系。单日语料较少时,训练结果更适合学习演示,不宜直接据此推断稳定的语义关系。
评论
发表评论