开发者社区 问答 正文

统计一个文本中单词频次最高的10个单词?

统计一个文本中单词频次最高的10个单词?

展开
收起
珍宝珠 2019-11-11 11:32:45 3032 分享
分享
版权
举报
1 条回答
写回答
取消 提交回答
  • import re
    
    # 方法一
    def test(filepath):
        
        distone = {}
    
        with open(filepath) as f:
            for line in f:
                line = re.sub("\W+", " ", line)
                lineone = line.split()
                for keyone in lineone:
                    if not distone.get(keyone):
                        distone[keyone] = 1
                    else:
                        distone[keyone] += 1
        num_ten = sorted(distone.items(), key=lambda x:x[1], reverse=True)[:10]
        num_ten =[x[0] for x in num_ten]
        return num_ten
        
     
    # 方法二 
    # 使用 built-inCounter 里面的 most_common
    import re
    from collections import Counter
    
    
    def test2(filepath):
        with open(filepath) as f:
            return list(map(lambda c: c[0], Counter(re.sub("\W+", " ", f.read()).split()).most_common(10)))
    
    2019-11-11 13:14:56 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答地址:
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等