验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Python统计词频的方法有哪些

阅读:390 来源:乙速云 作者:代码code

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))
分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>