微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python统计词频的方法有哪些

本文小编为大家详细介绍“Python统计词频的方法有哪些”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python统计词频的方法有哪些”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

方法一:运用集合去重方法

 def word_count1(words,n):
    word_list = []
    for word in set(words):
        num = words.counts(word)
        word_list.append([word,num])
        word_list.sort(key=lambda x:x[1], reverse=True)
    for i in range(n):
        word, count = word_list[i]
        print('{0:<15}{1:>5}'.format(word, count))

说明:运用集合对文本字符串列表去重,这样统计词汇不会重复,运用列表的counts方法统计频数,将每个词汇和其出现的次数打包成一个列表加入到word_list中,运用列表的sort方法排序,大功告成。

方法二:运用字典统计

def word_count2(words,n):
    counts = {}
    for word in words:
        if len(word) == 1:
            continue
        else:
            counts[word] = counts.get(word, 0) + 1
    items = list(counts.items())
    items.sort(key=lambda x:x[1], reverse=True)
    for i in range(n):
        word, count = items[i]
        print("{0:<15}{1:>5}".format(word, count))

方法三:使用计数器

def word_count3(words,n):
    from collections import Counter
    counts = Counter(words)
    for ch in "":  # 删除一些不需要统计的元素
        del counts[ch]
    for word, count in counts.most_common(n):  # 已经按数量大小排好了
        print("{0:<15}{1:>5}".format(word, count))

读到这里,这篇“Python统计词频的方法有哪些”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容文章,欢迎关注编程之家行业资讯频道。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐