如何计算多个标记化单词列表中最常见的 10 个单词
How do I count the 10 most common words in a multiple lists of tokenized words
我有一个数据集,其中包含大量标记化单词列表。
例如:
['apple','banana','tomato']
['tomato','tree','pikachu']
我有大约 40,000 个这样的列表,我想从所有 40,000 个列表中统计出 10 个最常见的单词。
有人知道吗?
您可以使用 itertools.chain
and take the most common words using 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)]
我有一个数据集,其中包含大量标记化单词列表。 例如:
['apple','banana','tomato']
['tomato','tree','pikachu']
我有大约 40,000 个这样的列表,我想从所有 40,000 个列表中统计出 10 个最常见的单词。
有人知道吗?
您可以使用 itertools.chain
and take the most common words using 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)]