zoukankan      html  css  js  c++  java
  • 获取单词列表出现频率最高的单词

    words = [
        'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
        'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
        'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
        'my', 'eyes', "you're", 'under'
    ]
    from collections import Counter
    word_counts = Counter(words)
    top_three = word_counts.most_common(3)
    print(top_three)

    输出

    [('eyes', 8), ('the', 5), ('look', 4)]

    作为输入, Counter 对象可以接受任意的由可哈希(hashable)元素构成的序列对象。 在底层实现上,一个 Counter 对象就是一个字典,将元素映射到它出现的次数上。比如:

    >>> word_counts['not']
    1
    >>> word_counts['eyes']
    8
    >>>

    如果你想手动增加计数,可以简单的用加法:

    >>> morewords = ['why','are','you','not','looking','in','my','eyes']
    >>> for word in morewords:
    ...     word_counts[word] += 1
    ...
    >>> word_counts['eyes']
    9
    >>>

    或者你可以使用 update() 方法:

    >>> word_counts.update(morewords)
    >>>

    Counter 实例一个鲜为人知的特性是它们可以很容易的跟数学运算操作相结合。比如:

    >>> a = Counter(words)
    >>> b = Counter(morewords)
    >>> a
    Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,
    "you're": 1, "don't": 1, 'under': 1, 'not': 1})
    >>> b
    Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,
    'my': 1, 'why': 1})
    >>> # Combine counts
    >>> c = a + b
    >>> c
    Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2,
    'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1,
    'looking': 1, 'are': 1, 'under': 1, 'you': 1})
    >>> # Subtract counts
    >>> d = a - b
    >>> d
    Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,
    "you're": 1, "don't": 1, 'under': 1})
    >>>

    毫无疑问, Counter 对象在几乎所有需要制表或者计数数据的场合是非常有用的工具。 在解决这类问题的时候你应该优先选择它,而不是手动的利用字典去实现。

  • 相关阅读:
    QT visual stuido 集成插件不能打开ui文件的原因
    KLSudoku 1.2 数独游戏软件发布
    QT for linux 的错误 undefined reference to 'FcFreeTypeQueryFace' 的解决方法
    tp3.2源码解析——入口文件
    关于php调用.net的web service 踩过的坑
    CentOS7 LNMP+phpmyadmin环境搭建(二、LNMP环境搭建)
    CentOS7 LNMP+phpmyadmin环境搭建(一、虚拟机及centos7安装)
    php无限分类
    php的文件引用
    CentOS7 LNMP+phpmyadmin环境搭建(三、安装phpmyadmin)
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10577639.html
Copyright © 2011-2022 走看看