【问题标题】:How do I count the 10 most common words in a multiple lists of tokenized words如何计算多个标记化单词列表中最常见的 10 个单词
【发布时间】:2019-05-15 14:56:13
【问题描述】:

我有一个包含许多标记化单词列表的数据集。 例如:

['apple','banana','tomato']
['tomato','tree','pikachu']

我有大约 40k 个这样的列表,我想将所有 40k 个列表中的 10 个最常见的词一起计算。

有人知道吗?

【问题讨论】:

    标签: python count nlp word


    【解决方案1】:

    您可以使用itertools.chain 展平嵌套列表,并使用Counter 及其most_common 方法获取最常用的单词:

    from itertools import chain
    from collections import Counter
    
    l = ['apple','banana','tomato'],['tomato','tree','pikachu']
    
    Counter(chain(*l)).most_common(10)
    # [('tomato', 2), ('apple', 1), ('banana', 1), ('tree', 1), ('pikachu', 1)]
    

    【讨论】:

      【解决方案2】:

      我建议将您的列表合并到一个列表中,例如

      list_of_lists = [['apple','banana','tomato'],['tomato','tree','pikachu']]
      
      import itertools
      flat_list = list(itertools.chain(*list_of_lists))
      

      然后使用 Counter 计算您的代币并选择前 10 个

      from collections import Counter
      counter_of_flat_list = Counter(flat_list)
      
      print(counter_of_flat_list.most_common(10)) # print top 10
      

      [('tomato', 2), ('apple', 1), ('banana', 1), ('tree', 1), ('pikachu', 1)]

      【讨论】:

        【解决方案3】:

        使用字典的解决方案

        arrays = [['apple','banana','tomato'],['tomato','tree','pikachu']]
        d = dict()
        for array in arrays:
            for item in array:
                if item in d:
                    d[item] += 1
                else:
                    d[item] = 1
        print(sorted( ((v,k) for k,v in d.items()), reverse=True)[:10])
        

        输出

        [('tomato', 2), ('apple', 1), ('banana', 1), ('tree', 1), ('pikachu', 1)]
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-18
        • 2019-05-21
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 1970-01-01
        • 2016-03-01
        相关资源
        最近更新 更多