我想通过以下条件从列表中提交一些令牌。1)token长度大于5 2)出现频率(原文中)大于100
我使用了以下代码
#token_list is a list object containing tokenized words from raw text
from collections import Counter
c = Counter(token_list)
selected_tokens = [word for word in token_list if len(word) > 5 and c.item[2] > 100]
selected_tokens
但是好像拿不到。我相信错误来自 'c.item[2]' 但不太了解 'Counter()' 命令背后的机制。
如果有人能就此启发我,我将不胜感激。
谢谢你。
有人说filter
吗?
selected_tokens = list(filter(lambda x: len(x) > 5 and c[x] > 100, token_list))
此外,您还可以使用 访问计数器计数c[...]
。此外,您可能需要警惕案例问题(不同案例中出现的相同词)。
如果您想要速度,请改用列表理解:
selected_tokens = [x for x in token_list if len(x) > 5 and c[x] > 100]
如果您希望获得满足您条件的单词而不会出现不需要的重复项,请使用一组set
而不是一组:
token_set = set(token_list)
selected_tokens = [x for x in token_set if if len(x) > 5 and c[x] > 100]
当心,订单丢失。如果您想要没有重复的订单,请使用OrderedDict
(python < 3.6 或dict
(python >= 3.6)。
dict_ = OrderedDict()
for t in token_list:
dict_[t] = None
selected_tokens = [x for x in dict_ if len(x) > 5 and c[x] > 100]
如果 adict
不这样做,您可以查看OrderedSet
配方并实现相同效果的东西:
token_set = OrderedSet(token_list)
selected_tokens = [x for x in token_set if ...] # as usual
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句