去年在整理古典文学资料时,我发现人工分析四大名著的人物关系、情节脉络需要耗费大量时间。作为Python开发者,自然想到用NLP技术来自动化这个过程。经过三个月的实践,我摸索出一套完整的解决方案,不仅能快速提取文本特征,还能在VS Code里直接调用AI模型进行深度分析。
这套方法特别适合:
python复制# 核心库清单
import jieba # 中文分词
import gensim # 主题建模
from sklearn.feature_extraction.text import TfidfVectorizer # 特征提取
import spacy # 实体识别
# 推荐使用conda创建专用环境
conda create -n nlp_classic python=3.8
conda activate nlp_classic
注意:spacy需要单独安装中文语言包:
bash复制python -m spacy download zh_core_web_sm
四大名著txt文件建议从权威渠道获取,我使用的是中华书局电子版。预处理时特别注意:
python复制def clean_text(text):
text = re.sub(r'第[一二三四五六七八九十百]+回', '', text)
text = text.translate(str.maketrans(',。!?;:“”‘’', ',.!?;:""\'\''))
return text
使用基于共现分析的方案:
python复制# 自定义人物词典示例
jieba.load_userdict('characters.dic') # 每行格式: "人名 10 nr"
# 共现矩阵生成
window_size = 50 # 最佳实践值
co_occurrence = defaultdict(int)
for i in range(len(tokens)-window_size):
window = tokens[i:i+window_size]
characters = set([t for t in window if t in character_names])
for pair in itertools.combinations(characters, 2):
co_occurrence[tuple(sorted(pair))] += 1
采用LDA模型分章节分析:
python复制# 分章节处理
chapters = re.split(r'第[一二三四五六七八九十百]+回', text)
texts = [[word for word in jieba.cut(chap) if word not in stopwords] for chap in chapters]
# 构建LDA模型
dictionary = gensim.corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lda = gensim.models.LdaModel(corpus=corpus, id2word=dictionary, num_topics=10)
# 可视化
import pyLDAvis
pyLDAvis.enable_notebook()
vis = pyLDAvis.gensim.prepare(lda, corpus, dictionary)
vis
在VS Code中新建.ipynb文件,配置内核为之前创建的nlp_classic环境。推荐安装这些扩展:
实用技巧:用# %%标记代码单元格,可以像PyCharm一样分段执行
将训练好的模型封装为FastAPI服务:
python复制from fastapi import FastAPI
app = FastAPI()
@app.post("/analyze")
async def analyze(text: str):
tokens = [t for t in jieba.cut(text) if t not in stopwords]
bow = dictionary.doc2bow(tokens)
topics = lda[bow]
return {"topics": topics}
然后在VS Code的REST Client插件中测试:
code复制POST http://localhost:8000/analyze
Content-Type: application/json
{"text": "却说玄德访孔明两次不遇"}
分词优化:古典文学中存在大量现代汉语不用的词汇,建议:
内存管理:
python复制# 大文件处理使用生成器
def chunk_reader(filepath, size=1024*1024):
with open(filepath, 'r', encoding='gb18030') as f:
while chunk := f.read(size):
yield chunk
模型选择:
可视化技巧:
python复制# 人物关系图优化
import networkx as nx
G = nx.Graph()
for pair, weight in co_occurrence.items():
if weight > 5: # 过滤低频关系
G.add_edge(pair[0], pair[1], weight=weight)
# 使用spring_layout避免节点重叠
pos = nx.spring_layout(G, k=0.5)
这套方法已经帮助我完成了《红楼梦》人物关系变迁的定量研究,相比传统人工分析方法效率提升了20倍。特别是在VS Code中实现全流程开发,调试效率比传统 Notebook 环境高出许多。