美文网首页
python 词频统计

python 词频统计

作者: 旺旺碎彬彬 | 来源:发表于2018-10-07 12:08 被阅读0次

"""Count words."""

def count_words(s, n):

    """Return the n most frequently occuring words in s."""

    from operator import itemgetter, attrgetter 

    # TODO: Count the number of occurences of each word in s

    strl_ist = s.replace('\n', ' ').lower().split(' ')

    count_dict = {}

    for str in strl_ist:

        if str in count_dict.keys():

            count_dict[str] = count_dict[str] + 1

        else:

            count_dict[str] = 1

    # TODO: Sort the occurences in descending order (alphabetically in case of ties)

    count_list=sorted(count_dict.iteritems(),key=itemgetter(1),reverse=True)

    top_n = count_list[0:n]

    # TODO: Return the top n most frequent words.

    return top_n

def test_run():

    """Test count_words() with some inputs."""

    print count_words("cat bat mat cat bat cat", 3)

    print count_words("betty bought a bit of butter but the butter was bitter", 3)

if __name__ == '__main__':

    test_run()

相关文章

  • python统计词频

    一、最终目的 统计四六级真题中四六级词汇出现的频率,并提取对应的例句,最终保存到SQL数据库中。 二、处理过程 1...

  • python统计词频

    一、使用re库进行识别 1、代码 2、参考 python--10行代码搞定词频统计python:统计历年英语四六级...

  • python 词频统计

    """Count words.""" def count_words(s, n): """Return the...

  • Python | 词频统计

    最近工作蛮忙的,就简单练习一下python基础吧。 本周的练习是词频统计,主要使用了以下几个函数: text.sp...

  • Python词频统计

    场景: 现在要统计一个文本中的词频,然后按照频率的降序进行排列

  • Python词频统计

    1.合并数据文件 2.词频统计

  • python词频统计实例

    项目概述 通过两个Python文件实现一个简单的词频统计。 本工程共有4个文件: file01:要统计的词频文件。...

  • Python 进行词频统计

    1. 利用字典map实现 2.利用collections模块中的Counter对象 3. 算法:...

  • Python实现词频统计

    《百年孤独》词频统计 学习更多?欢迎关注本人公众号:Python无忧

  • 教你用Python进行中文词频统计

    Python是用于数据挖掘的利器 用Python可以用来做很多很好玩的东西,下面就来用Python来进行词频统计 ...

网友评论

      本文标题:python 词频统计

      本文链接:https://www.haomeiwen.com/subject/tqklaftx.html