网站/小程序/APP个性化定制开发,二开,改版等服务,加扣:8582-36016

本文主要介绍了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统计词频的几种方法小结的文章就介绍到这了


评论 0

暂无评论
0
0
0
立即
投稿
发表
评论
返回
顶部