import re
f = open("八十天环游地球.txt",'r',encoding='utf8')
lines = f.read()
title = re.findall('(第.{1,3}章.*)\\n',lines)
parts = re.sub('(第.{1,3}章.*)','@',lines) #将章节题目替换成一个标记符号
part = parts.split('@') #根据标记符号切分全文
part = part[1:] #因为切分后part[0]是一个空字符,这样切分是为了让标题和段落一一对应
zip函数提取获取每一个章节的词频
这里是获取每章出现最多的词频。
import jieba
for i,j in zip(title,part):
counts = {}
words = jieba.lcut(i + j)
for word in words:
if word in '\n ':
continue
elif len(word) >=2:
counts[word] = counts.get(word,0) + 1
lt = list(counts.items())
lt.sort(key=lambda x: x[1],reverse=True)
charter = re.findall('(第.*章)',i)[0]
print("{} {} {}".format(charter,lt[0][0],lt[0][1]))