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

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条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置