一、技术栈准备
本次实战所需的核心库:
- 基础库:
os(文件/路径处理)、re(正则匹配)、pandas(数据结构化); - 中文处理:
jieba(中文分词),支持自定义词库; - 算法库:
sklearn.feature_extraction.text.TfidfVectorizer(TF-IDF 特征提取)。
《红楼梦》文本分析通过 Python 实现文本结构化、特征量化与结果分析。项目核心逻辑包含正则匹配定位章节拆分全文为独立文件,利用 jieba 分词适配古典文学词汇并加载自定义词库,结合停用词过滤去除无意义字符。最终通过 sklearn 的 TF-IDF 算法将分词文本转化为向量矩阵,量化词汇重要性并按值降序排序提取每回核心关键词。该方法可快速适配其他长篇文本的分析需求,无需手动指定路径即可自动化处理章节数据。
本次实战所需的核心库:
os(文件/路径处理)、re(正则匹配)、pandas(数据结构化);jieba(中文分词),支持自定义词库;sklearn.feature_extraction.text.TfidfVectorizer(TF-IDF 特征提取)。import os
import re
import pandas as pd
# ===================== 核心优化:适配文本格式 + 解决报错 =====================
# 1. 确保保存目录存在(避免路径不存在报错)
output_dir = r'.\红楼梦\分卷 1'
os.makedirs(output_dir, exist_ok=True)
# 2. 打开源文件(使用 with 语句自动关闭,更安全)
with open(r'.\红楼梦\红楼梦.txt', encoding='utf-8') as file:
flag = 0 # 用来标记当前是不是在第一次保存文件
juan_file = None # 初始化文件对象,避免未定义报错
# 定义:清理 Windows 非法文件名字符(解决 OSError 报错)
def clean_filename(filename):
illegal_chars = r'[\\/:*?"<>|,。?!;:"''《》()()【】]'
clean_name = re.sub(illegal_chars, '', filename)
return clean_name[:50] + '.txt'
# 定义:精准匹配'卷 + 回'标题(适配文本中'上卷 第一回 XXX'格式)
chapter_pattern = re.compile(r'^[ \s]*([上下]卷\s+第 [一二三四五六七八九十百零]+回.*)$', re.MULTILINE)
for line in file:
line_strip = line.strip()
match = chapter_pattern.match(line_strip)
if match:
juan_title = match.group(1).strip()
juan_name = clean_filename(juan_title)
path = os.path.join(output_dir, juan_name)
print(f"正在创建文件:{path}")
if flag == 0:
if juan_file:
juan_file.close()
juan_file = open(path, 'w', encoding='utf-8')
juan_file.write(line)
flag = 1
else:
juan_file.close()
juan_file = open(path, 'w', encoding='utf-8')
juan_file.write(line)
continue
if juan_file is not None:
juan_file.write(line)
if juan_file:
juan_file.close()
print(f"\n✅ 拆分完成!共生成{flag}个卷文件,保存在:{output_dir}")
juan_file 变量管理当前写入的文件,确保章节内容正确归属。import pandas as pd
import os
filePaths = []
fileContents = []
for root, dirs, files in os.walk(r'.\红楼梦\分卷 1'):
for name in files:
filePath = os.path.join(root, name)
filePaths.append(filePath)
f = open(filePath, 'r', encoding='utf-8')
fileContent = f.read()
f.close()
fileContents.append(fileContent)
corpos = pd.DataFrame({
'filePath': filePaths,
'fileContent': fileContents
})
print(corpos)
import jieba
import pandas as pd
jieba.load_userdict(r'.\红楼梦\红楼梦词库.txt')
stopwords = pd.read_csv(r'.\红楼梦\StopwordsCN.txt', encoding='utf8', engine='python', index_col=False)
file_to_jieba = open(r'.\红楼梦\分词后汇总 1.txt', 'w', encoding='utf-8')
for index, row in corpos.iterrows():
fileContent = row['fileContent']
segs = jieba.cut(fileContent)
juan_ci = ''
for seg in segs:
if seg not in stopwords.iloc[:, 0].values and len(seg.strip()) > 0:
juan_ci = juan_ci + seg + ' '
file_to_jieba.write(juan_ci + '\n')
file_to_jieba.close()
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
inFile = open(r".\红楼梦\分词后汇总 1.txt", 'r', encoding='utf-8')
corpus = inFile.readlines()
vectorizer = TfidfVectorizer()
tfidf = vectorizer.fit_transform(corpus)
wordlist = vectorizer.get_feature_names_out()
df = pd.DataFrame(tfidf.T.todense(), index=wordlist)
for i in range(len(corpus)):
featurelist = df.iloc[:, i].to_list()
resdict = {}
for j in range(0, len(wordlist)):
resdict[wordlist[j]] = featurelist[j]
resdict = sorted(resdict.items(), key=lambda x: x[1], reverse=True)
print('第{}回的核心关键词:'.format(i+1), resdict[0:10])

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online