【问题标题】:Python count tuples occurence in listPython计数列表中出现的元组
【发布时间】:2017-04-05 13:22:25
【问题描述】:

有没有办法计算每个元组在这个标记列表中出现的次数?

我尝试了count 方法,但它不起作用。

这是列表:

['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay']

这些是基于列表的元组:

('hello', 'how')
('how', 'are')
('are','you')
('you', 'doing')
('doing', 'today')
('today', 'are')
('you', 'okay')

我希望结果是这样的

('hello', 'how')1
('how', 'are')1
('are','you')2
('you', 'doing')1
('doing', 'today')1
('today', 'are')1
('you', 'okay')1

【问题讨论】:

  • 使用Counter怎么样?
  • 令牌是否必须在列表中彼此相邻才能匹配元组?
  • @chbchb55:这或多或少是 n-gram 的概念。
  • 谢谢!我对此很陌生,但是如果我想使用 n-gram 作为一个词汇表,其中每个都列出一次,然后检查它们在许多不同列表中出现的次数,是否还有一种方法可以这样做?跨度>

标签: python counter n-gram


【解决方案1】:

您可以轻松地为此使用Counter。计算 n-gram 的通用函数如下:

from collections import Counter
from itertools import islice

def count_ngrams(iterable,n=2):
    return Counter(zip(*[islice(iterable,i,None) for i in range(n)]))

这会生成:

>>> count_ngrams(['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay'],2)
Counter({('are', 'you'): 2, ('doing', 'today'): 1, ('you', 'doing'): 1, ('you', 'okay'): 1, ('today', 'are'): 1, ('how', 'are'): 1, ('hello', 'how'): 1})
>>> count_ngrams(['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay'],3)
Counter({('are', 'you', 'okay'): 1, ('you', 'doing', 'today'): 1, ('are', 'you', 'doing'): 1, ('today', 'are', 'you'): 1, ('how', 'are', 'you'): 1, ('doing', 'today', 'are'): 1, ('hello', 'how', 'are'): 1})
>>> count_ngrams(['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay'],4)
Counter({('doing', 'today', 'are', 'you'): 1, ('today', 'are', 'you', 'okay'): 1, ('are', 'you', 'doing', 'today'): 1, ('how', 'are', 'you', 'doing'): 1, ('you', 'doing', 'today', 'are'): 1, ('hello', 'how', 'are', 'you'): 1})

【讨论】:

    【解决方案2】:

    此解决方案需要第三方模块 (iteration_utilities.Iterable),但应该可以满足您的需求:

    >>> from iteration_utilities import Iterable
    
    >>> l = ['hello', 'how', 'are', 'you', 'doing', 'today', 'are', 'you', 'okay']
    
    >>> Iterable(l).successive(2).as_counter()
    Counter({('are', 'you'): 2,
             ('doing', 'today'): 1,
             ('hello', 'how'): 1,
             ('how', 'are'): 1,
             ('today', 'are'): 1,
             ('you', 'doing'): 1,
             ('you', 'okay'): 1})
    

    【讨论】:

    • 谢谢!如果我想使用 n-gram 作为词汇表,然后对照许多列表检查这个词汇表,你知道该怎么做吗?
    • 不确定你的意思。也许这可能需要另一个问题,您可以更清楚地解释您需要什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    相关资源
    最近更新 更多