统计一下《罗密欧与朱丽叶》中,两人的名字中各出现了多少次
import jieba
txt = open("罗密欧与朱丽叶.txt","r",encoding='utf-8').read() ##读入整个文件的内容,参数为前多少字节流
words = jieba.lcut(txt) ##返回单词,不重复
counts = {}
for word in words:
if len(word) ==1:
continue
else:
counts[word] = counts.get(word,0)+1 ##键存在就返回相应值,否则返回默认值,word为字典的键
items = list(counts.items()) ##返回所有的键值对,并形成列表
items.sort(key=lambda x:x[1],reverse=True) ##输入,输出、后面的x: x[1] 为对前面的对象中的第二维数据(即value)的值进行排序,倒序reverse默认为False升序
print("罗密欧与朱丽叶各出现了多少次?")
for i in range(2):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))##序号、填充、对齐方式、占位、精度、类型