用Python爬虫+GPT-4分析肯尼迪演说词频:一次文本挖掘与历史语料处理的实战
用Python解析肯尼迪演说从词频统计到AI深度解读的技术实践1961年那个寒冷的1月早晨约翰·F·肯尼迪站在国会大厦台阶上发表的演说至今仍被视为20世纪最具影响力的政治演讲之一。作为技术从业者我们如何用现代工具来解析这份历史文本本文将带你用Python构建完整的分析流程——从网络爬虫获取原始文本到NLP技术提取关键特征最后用大语言模型生成专业解读报告。1. 环境准备与数据获取在开始分析前我们需要搭建合适的工作环境。推荐使用Anaconda创建独立的Python 3.8环境这能避免依赖冲突。核心工具库包括# 创建conda环境 conda create -n speech_analysis python3.8 conda activate speech_analysis # 安装核心库 pip install requests beautifulsoup4 nltk spacy pandas matplotlib python -m spacy download en_core_web_sm可可英语网站保存着完整的演说中英文对照文本我们可以用Requests和BeautifulSoup构建爬虫import requests from bs4 import BeautifulSoup def crawl_keke_english(url): headers {User-Agent: Mozilla/5.0} response requests.get(url, headersheaders) soup BeautifulSoup(response.text, html.parser) # 定位演讲文本区域 content_div soup.find(div, {class: article-content}) paragraphs [p.get_text(stripTrue) for p in content_div.find_all(p)] return \n.join(paragraphs) # 示例URL - 实际使用时需替换为可可英语真实地址 speech_url https://www.kekenet.com/Article/202201/123456.shtml speech_text crawl_keke_english(speech_url)注意实际爬取时应遵守网站的robots.txt规则并设置合理的请求间隔。对于频繁访问建议联系网站获取API接口或官方数据包。2. 文本预处理与词频分析原始文本需要经过多步清洗才能用于分析。我们构建的处理管道包括文本规范化统一大小写、去除标点停用词过滤移除常见无意义词汇词形还原将单词还原为基本形式import re from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer import nltk nltk.download(stopwords) nltk.download(wordnet) def preprocess_text(text): # 保留字母和基本标点 text re.sub(r[^a-zA-Z\s], , text.lower()) # 分词并过滤停用词 stop_words set(stopwords.words(english)) words [word for word in text.split() if word not in stop_words] # 词形还原 lemmatizer WordNetLemmatizer() return [lemmatizer.lemmatize(word) for word in words] processed_words preprocess_text(speech_text)词频统计结果可以用Pandas进行排序和可视化import pandas as pd from collections import Counter import matplotlib.pyplot as plt word_counts Counter(processed_words) df pd.DataFrame(word_counts.most_common(20), columns[Word, Frequency]) plt.figure(figsize(12,6)) df.plot.bar(xWord, yFrequency, rot45) plt.title(Top 20 Words in Kennedy Speech) plt.tight_layout() plt.show()典型输出表格示例排名单词频率词性语义权重1freedom28名词0.922nation19名词0.873pledge15动词0.854world14名词0.835new12形容词0.783. 高级NLP特征提取基础的词频统计只能揭示表面特征我们需要更深入的分析技术3.1 命名实体识别使用spaCy提取演讲中的关键实体import spacy nlp spacy.load(en_core_web_sm) doc nlp(speech_text) entities [(ent.text, ent.label_) for ent in doc.ents] entity_counts pd.DataFrame(entities, columns[Entity, Type])\ .groupby([Type, Entity]).size().unstack().fillna(0)3.2 情感分析通过VADER情感分析器检测情绪变化from nltk.sentiment import SentimentIntensityAnalyzer nltk.download(vader_lexicon) analyzer SentimentIntensityAnalyzer() sentences nltk.sent_tokenize(speech_text) sentiment_scores [analyzer.polarity_scores(sent) for sent in sentences]3.3 主题建模使用LDA算法发现潜在主题from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation vectorizer CountVectorizer(max_df0.95, min_df2) dtm vectorizer.fit_transform(sentences) lda LatentDirichletAllocation(n_components3) lda.fit(dtm) for idx, topic in enumerate(lda.components_): print(fTopic {idx}:) print([vectorizer.get_feature_names_out()[i] for i in topic.argsort()[-5:]])4. GPT-4辅助分析与报告生成将前序分析结果结构化后我们可以用GPT-4 API生成专业解读import openai analysis_prompt f 基于以下对肯尼迪就职演说的分析结果请生成一份专业报告 1. 高频词{df.head(10).to_dict()} 2. 命名实体{entity_counts.head().to_dict()} 3. 情感趋势{sentiment_scores[:3]} 请重点解读 - 演说核心主题的构建方式 - 修辞手法的技术特点 - 历史语境下的特殊表达 response openai.ChatCompletion.create( modelgpt-4, messages[{role: user, content: analysis_prompt}], temperature0.7 ) print(response[choices][0][message][content])典型分析报告会包含以下技术观察点平行结构的密集使用Let both sides...重复出现7次三位一体修辞模式pay any price, bear any burden, meet any hardship未来导向词汇占比达到文本的37%集体代词we/our使用频率是传统政治演讲的1.8倍5. 可视化与交互探索最终的Jupyter Notebook可以整合以下交互元素from ipywidgets import interact interact def explore_section(start: (0, len(sentences)-10), length(1, 10)): section .join(sentences[start:startlength]) sentiment analyzer.polarity_scores(section) plt.figure(figsize(10,4)) pd.Series(sentiment).plot.bar() plt.title(fSentiment Analysis: Paragraphs {start}-{startlength}) plt.ylim(-1,1) plt.show() return { text: section, word_count: len(section.split()), avg_word_length: sum(len(w) for w in section.split())/len(section.split()) }对于希望深入研究的开发者还可以尝试比较不同总统就职演说的词汇特征构建历时性分析看修辞风格演变开发Flask应用将分析流程产品化这个项目展示了如何将传统文本分析与现代AI技术结合。在实际操作中最耗时的部分往往是数据清洗和参数调优——比如spaCy模型对历史文本的特殊处理或者LDA主题数的确定。建议先在小样本上测试完整流程再扩展到更大规模的语料分析。