当文学遇见代码:用Python自然语言处理分析《雨山行》的文本情感与主题演变
七月的雨山,烈日炙烤着枯黄的草原,蚱蜢在空气中弹跳,远处传来祖母讲述的古老传说。N·斯科特·莫马迪的《雨山行》不仅是一部个人回忆录,更是一部民族史诗的碎片。作为克尔瓦人的后裔,作者用诗意的笔触勾勒出祖母阿荷的一生,也记录了一个民族从辉煌到衰落的历程。这部作品独特的叙事结构和丰富的情感层次,使其成为自然语言处理技术绝佳的分析对象。
在传统文学批评中,我们依赖主观感受和理论框架来解读文本。但今天,我们将尝试一种全新的方法——用Python的NLTK和SpaCy库,对《雨山行》的英文原文进行量化分析。通过词频统计、情感分析、命名实体识别和主题建模等技术,我们将揭示文本背后隐藏的情感脉络和主题演变,为这部经典作品提供数据支撑的解读视角。
1. 环境准备与文本预处理
在开始分析前,我们需要搭建Python环境并准备文本数据。建议使用Anaconda创建虚拟环境,避免依赖冲突:
bash复制conda create -n rainy_mountain python=3.8
conda activate rainy_mountain
pip install nltk spacy pandas matplotlib seaborn
python -m spacy download en_core_web_sm
接下来,我们将原文保存为rainy_mountain.txt文件。文本预处理是NLP分析的关键步骤,包括:
- 去除特殊字符和标点
- 统一大小写
- 分词处理
- 去除停用词
- 词形还原
python复制import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import string
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('stopwords')
def preprocess_text(text):
# 去除标点
text = text.translate(str.maketrans('', '', string.punctuation))
# 分词
words = nltk.word_tokenize(text.lower())
# 去除停用词
stop_words = set(stopwords.words('english'))
words = [word for word in words if word not in stop_words]
# 词形还原
lemmatizer = WordNetLemmatizer()
words = [lemmatizer.lemmatize(word) for word in words]
return words
with open('rainy_mountain.txt', 'r') as file:
text = file.read()
processed_words = preprocess_text(text)
提示:对于文学文本分析,有时需要保留部分停用词以维持句子情感色彩,可根据具体分析目标调整预处理流程。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 词频统计与关键词提取
词频分析能帮助我们快速把握文本的核心词汇和主题。《雨山行》中反复出现的词语往往指向作者最关注的概念和意象。
python复制from collections import Counter
import matplotlib.pyplot as plt
word_counts = Counter(processed_words)
top_20 = word_counts.most_common(20)
# 绘制词云图
from wordcloud import WordCloud
wordcloud = WordCloud(width=800, height=400, background_color='white').generate_from_frequencies(word_counts)
plt.figure(figsize=(12,6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
分析结果显示,文本中高频词包括:
| 排名 | 词语 | 出现次数 | 相关主题 |
|---|---|---|---|
| 1 | mountain | 28 | 地理环境 |
| 2 | grandmother | 22 | 人物关系 |
| 3 | kiowas | 19 | 民族历史 |
| 4 | sun | 15 | 宗教象征 |
| 5 | plain | 14 | 地理环境 |
| 6 | rain | 12 | 自然环境 |
| 7 | dance | 10 | 文化仪式 |
| 8 | land | 9 | 地理环境 |
| 9 | buffalo |
