【问题标题】:How to count how many times a word appears in a list in python [duplicate]如何计算一个单词在python列表中出现的次数[重复]
【发布时间】:2019-06-01 09:42:13
【问题描述】:

我在 python 中有以下列表

texts = [
    ["great", "even", "for", "the", "non", "runner", "this", "sound",
     "track", "was", "brilliant"],
    ["cannot", "recommend", "as", "a", "former", "comrade", "i", "did",
     "not", "want", "to", "have", "to", "do", "this"]
]

我想浏览列表并计算每个单词出现在其中的频率。

我尝试使用 length() 计算单个单词,结果得到 2,这意味着它不起作用。

有什么方法可以计算一个单词在列表中出现的频率,因为我打算将计数的单词存储在一个新列表中,并将它的频率存储在另一个列表中。

提前致谢

【问题讨论】:

  • 如果没有看到您的原始代码,我们将不知道如何在您现有的代码库中解决问题。请发布您的mcve,并详细说明需要修改的内容。解释问题,以及该输入应该产生什么输出。
  • answer 重复。

标签: python python-3.x


【解决方案1】:

首先要注意的是texts 可能是一个嵌套列表,这也是为什么len(texts) 会得到2,因为texts 包含2 个子列表。

如果要遍历单个单词,则需要遍历子列表,然后遍历子列表中的单词。幸运的是,Python 的列表推导可以嵌套:

[word for words in texts for word in words]

至于计数:标准库有一个专门用于此目的的字典类:collections.Counter:

word_counts = collections.Counter(word for words in texts for word in words)

这将为您提供一个字典,将单个单词映射到它们的出现次数。

【讨论】:

    【解决方案2】:

    一个班轮:

    from collections import Counter
    from itertools import chain
    
    texts = [["a", "b"], ["a", "c"]]
    
    words_count = Counter(chain(*texts))
    print(words_count)
    
    >> Counter({'a': 2, 'b': 1, 'c': 1})
    

    【讨论】:

      【解决方案3】:

      您可以为此使用Counter

      texts = [
          ["great", "even", "for", "the", "non", "runner", "this", "sound",
            "track", "was", "brilliant"],
          ["cannot", "recommend", "as", "a", "former", "comrade", "i", "did",
            "not", "want", "to", "have", "to", "do", "this"]
      ]
      
      for text in texts:
          cnt = Counter()
          for word in text:
              cnt[word] += 1
          print(cnt)
      

      【讨论】:

      • 请注意texts 是一个嵌套列表。
      【解决方案4】:

      你可以用Counter来统计字数:

      from collections import Counter
      
      texts = [["great", "even", "for", "the", "non", "runner", "this", "sound","track", "was", "brilliant"],
               ["cannot", "recommend", "as", "a", "former", "comrade", "i", "did", "not", "want", "to", "have", "to", "do", "this"]]
      
      for text in texts:
          print(Counter(text))
      
      # Counter({'great': 1, 'even': 1, 'for': 1, 'the': 1, 'non': 1, 'runner': 1, 'this': 1, 'sound': 1, 'track': 1, 'was': 1, 'brilliant': 1})
      # Counter({'to': 2, 'cannot': 1, 'recommend': 1, 'as': 1, 'a': 1, 'former': 1, 'comrade': 1, 'i': 1, 'did': 1, 'not': 1, 'want': 1, 'have': 1, 'do': 1, 'this': 1})
      

      来源:How do I count unique values inside a list

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-05
        • 1970-01-01
        • 2016-01-09
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        相关资源
        最近更新 更多