#CalHamletV1.py#英文统计程序
def getText():
txt = open("hamlet.txt", "r").read()
txt = txt.lower()
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格
return txt
hamletTxt = getText()
words = hamletTxt.split()#split默认用空格分割字符串,返回列表,后是无空格的单词列表
counts = {}#创建字典
for word in words:
counts[word] = counts.get(word,0) + 1#遍历字典的键并对相应值+1,达到统计目的
items = list(counts.items())#items函数返回所有键值对元组,再用list返回列表类型,其中每个元素都是一个键值对
items.sort(key=lambda x:x[1], reverse=True) #按照键值对中的【1】就是第二个元素排序,逆序==从大到小(默认从小到大)
for i in range(10):
word, count = items[i]#键值对赋值给word,count
print ("{0:<10}{1:>5}".format(word, count)
#CalThreeKingdomsV1.py
import jieba