iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python统计词频的几种方法小结
  • 203
分享到

Python统计词频的几种方法小结

Python统计词频Python文本词频统计 2023-03-01 17:03:14 203人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录方法一:运用集合去重方法方法二:运用字典统计方法三:使用计数器本文介绍python统计词频的几种方法,供大家参考 方法一:运用集合去重方法 def Word_count1(wo

本文介绍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统计词频的几种方法小结的文章就介绍到这了,更多相关Python统计词频内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python统计词频的几种方法小结

本文链接: https://www.lsjlt.com/news/198051.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作