希幼黎 2021-05-16 10:44 采纳率: 50%
浏览 190
已采纳

python统计单词词频

统计Hamlet文本文件中所有的的单词词频,并把词频排名前100的单词和出现频次保存到一个文本文件中,并将文件名统一格式为“姓名.txt”

  • 写回答

4条回答 默认 最新

  • 关注
    
    def getText():
        txt = open("C:/Users/Lenovo/Desktop/hamlet.txt", "r").read()
        txt = txt.lower()
        for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
            txt = txt.replace(ch," ")
        return txt
    
    hamletText = getText()
    words = hamletText.split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word,0) + 1
    items = list(counts.items())
    items.sort(key = lambda x:x[1],reverse = True)
    a=sum([len(line.split()) for line in open("C:/Users/Lenovo/Desktop/hamlet.txt", 'r')])
    #print(a)
    for i in range(a-1):
        word,count = items[i]
        print("{0:<10}{1:>5}".format(word,count))

    有帮助的话点个采纳,谢谢

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?