源码:
import content as content
import jieba
txt=open("F:\\作业\\2021年大三第一学期\\人工智能\\threekingdoms.txt","r",encoding="utf-8").read()
excludes={"将军","却说","荆州","二人","不可","不能","如此","商议","如何","主公","军士",
"左右","军马","引兵","次日","大喜","天下","东吴","于是","今日","不敢","魏兵",
"陛下","一人","都督"}
words=jieba.lcut(txt) #使用jieba的精确模式,返回一个列表类型的分词结果
counts={}
for word in words: #这句关键,用words列表中的每个单词去索引字典,
# 已经有这个键的话就把相应的值加1,没有的话就取值为0,再加1
if len(word)==1:
continue
elif word=="诸葛亮"or word=="孔明曰":
rword="孔明"
elif word=="关公"or word=="云长":
rword="关羽"
elif word=="玄德"or word=="玄德曰":
rword="刘备"
elif word=="孟德"or word=="丞相":
rword="曹操"
else:
rword=word
counts[rword]=counts.get(rword,0)+1
for word in excludes:
del counts[word] #将在excludes表中的词也去除
items=list(counts.items()) #将字典类型转换为list类型便于操作
items.sort(key=lambda x:x[1],reverse=True) #对一个列表,所有键值对的第2个元素进行排序,
# 默认是false,是从小到大,True的话就是从大到小,注意里面的'key='暂时记住这句,这是list的sort排序的lambda方法
f = open("F:\\作业\\2021年大三第一学期\\人工智能\\1.txt",'a+',encoding="utf-8")
for i in range(30):
#range里面的数字可以确定你需要多少个人物
word,count=items[i]
if len(word)==2:
print('{0:<5} {1:<12} {2:>6}'.format(i+1,word,count))
f.write('{1:<11} {2:>6}\n'.format(i + 1, word, count))
# 在于中间的{1:<12},汉字只算一个字符的话,会比空格位更宽一点,加个这样的if else判断下使文字对齐
else:
print('{0:<5} {1:<11} {2:>6}'.format(i+1,word,count))
f.write('{1:<11} {2:>6}\n'.format(i+1,word,count))
f.close()
运行结果页面:
结果输出到txt文本中