统计hamlet中的高频单词

# hamlet.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()  # 将文本转换为列表,方便数据处理,空格分开
counts = {}  # 创建空字典,键为单词,值为出现的次数
for word in words:
    counts[word] = counts.get(word, 0) + 1  # 对单词循环操作,对字典的值进行处理,没有出现,则出现次数给0,并且加1
items = list(counts.items())  # 将字典装入列表,目的同样是方便数据处理
items.sort(key=lambda x: x[1], reverse=True)  # 根据值的大小,也即单词的出现次数,进行由大到小的排序
for i in range(10):  # 选取出现次数最高的十个
    word, count = items[i]  # 键和值赋给变量
    print("{0:<10}{1:>5}".format(word, count))  # 格式化打印,0和1表示位置,:表示引导符,<10表示左对齐,占10个位置,>5表示右对齐,占5个位置

posted @ 2023-06-10 23:22  钢牙123  阅读(84)  评论(0)    收藏  举报