【问题标题】:Python: Add occurrences of a list element and its total count to another list, avoid adding duplicates [duplicate]Python:将列表元素的出现次数及其总数添加到另一个列表中,避免添加重复项[重复]
【发布时间】:2016-02-05 16:51:31
【问题描述】:

我有一个包含句子的文本语料库。 我希望计算每个单词的出现次数并避免多次添加任何单词(例如,多次出现的“,”必须添加一次才能返回类似 ',': 2047 的内容)

期望的输出:'partner': 7, 'meetings': 7, '14': 7, 'going': 7,etc。 我意识到我需要使用set() 来避免重复。但我不知道怎么做。目前,我通过说append only if not already in occurrences 来避免添加已经在列表中的元素

但这不起作用,因为我在结果中多次收到',':2047

我在示例代码中避免使用列表理解来增加读者的理解! :P

计算单词中单词[i]的出现次数

occurrences = []
for i in range(1, words.__len__() - 1):
    if words[i-1] not in occurrences:
        occurrences.append((words[i - 1], words.count(words[i - 1])))
print(occurrences)

【问题讨论】:

  • 使用collections.Counter
  • 我相信与重复的问题相比,我的问题更容易通过预期输出快速掌握。 IDC 如果这个被删除了。

标签: python list dictionary set


【解决方案1】:

使用collections.Counter:

word_count = Counter(words)

【讨论】:

    【解决方案2】:

    根据这个答案here 我应该像这样使用 Counter() :

    from collections import Counter
    ctr = Counter()
        for word in words:
            ctr[word] += 1
        print(ctr)
    

    【讨论】:

      猜你喜欢
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 2022-08-02
      • 2012-05-20
      • 2018-11-12
      • 1970-01-01
      相关资源
      最近更新 更多