簡體   English   中英

如何在多個標記化單詞列表中計算10個最常見的單詞

[英]How do I count the 10 most common words in a multiple lists of tokenized words

我有一個數據集,其中包含很多標記詞列表。 例如:

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

我有大約40k個這樣的列表,並且我想將所有40k列表中的10個最常用的詞加在一起。

有人知道嗎

您可以使用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)]

使用字典的解決方案

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)]

我建議將您的列表合並為一個列表,例如

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)]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM