【发布时间】:2019-05-15 14:56:13
【问题描述】:
我有一个包含许多标记化单词列表的数据集。 例如:
['apple','banana','tomato']
['tomato','tree','pikachu']
我有大约 40k 个这样的列表,我想将所有 40k 个列表中的 10 个最常见的词一起计算。
有人知道吗?
【问题讨论】:
我有一个包含许多标记化单词列表的数据集。 例如:
['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)]
【讨论】:
我建议将您的列表合并到一个列表中,例如
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)]
【讨论】:
使用字典的解决方案
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)]
【讨论】: