#三国人物用词统计 #1、打开文本文件,并read后把read的结果放到txt中 txt=open("threekingdoms.txt","r",encoding="utf-8").read() #2、英文分词里习惯将将符号替换为空格,但是中文分词用jieba库就不需要替换操作了。进行分词操作将分词放入words列表 import jieba words=jieba.lcut(txt) #3、建立words,抽取长度不为1的字符,组成新的字典dicwords exp=["却说","锦州","二人","将军","不可","不能","如此"] dicwords={} for i in words: if len(i)==1:#排除字符长度为1的 continue elif i in exp: continue elif i=="孔明曰" or i=="孔明": dicwords["孔明"]=dicwords.get("孔明",0)+1 elif i == "玄德曰" or i == "玄德": dicwords["玄德"] = dicwords.get("玄德", 0) + 1 else: dicwords[i]=dicwords.get(i,0)+1 #4、对列表中字符与出现的次数进行排序 lsdicwords=list(dicwords.items()) lsdicwords.sort(key=lambda x:x[1],reverse=True) #找出前十名用的高频词汇 n=0 for i in lsdicwords: name,times=i #print(name,times) n=n+1 if n==10: break #也可以这样写 for i in range(15): name,tiems=lsdicwords[i] print(name,times)