python用字典统计单词出现次数_如何使用字典理解来计算文档中每个单词的出现次数...

本文介绍了如何在Python中使用collections.Counter类有效地统计文本列表中每个单词的出现次数,包括直接更新Counter,使用列表推导式,以及通过itertools.chain扁平化列表的方法。
摘要由CSDN通过智能技术生成

就像其他答案中解释的一样,问题是字典理解会创建一个新字典,所以在新字典创建之前,您不会获得对它的引用。你不能对你正在做的事进行字典理解。在

鉴于此,您所做的就是重新实现^{}已经完成的工作。您只需使用Counter。示例-from collections import Counter

term_appearance = Counter()

for x in texts_list:

term_appearance.update(x)

演示-

^{pr2}$

如果你真的想在某种程度上理解这一点,你可以:from collections import Counter

term_appearance = Counter()

[term_appearance.update(x) for x in texts_list]

演示->>> l = [[1,2,3],[2,3,1],[5,4,2],[1,1,3]]

>>> from collections import Counter

>>> term_appearance = Counter()

>>> [term_appearance.update(x) for x in l]

[None, None, None, None]

>>> term_appearance

Counter({1: 4, 2: 3, 3: 3, 4: 1, 5: 1})

输出[None, None, None, None]来自生成该列表的列表理解(因为这是以交互方式运行的),如果在脚本中以python

您还可以使用^{}从文本列表创建一个扁平化列表,然后将其用于计数器。示例:from collections import Counter

from itertools import chain

term_appearance = Counter(chain.from_iterable(texts_list))

演示->>> from collections import Counter

>>> from itertools import chain

>>> term_appearance = Counter(chain.from_iterable(l))

>>> term_appearance

Counter({1: 4, 2: 3, 3: 3, 4: 1, 5: 1})

另外,你的原始代码中的另一个问题-{{term_appearance[l] : term_appearance[l] + 1 if l else term_appearance[l] : 1 for l in x} for x in texts_list}

这实际上是一个集合理解,其中嵌套了一个字典理解。在

这就是您得到错误-TypeError: unhashable type: 'dict'的原因。因为在第一次运行字典理解并创建一个dict之后,它正试图将其添加到set中。但是字典是不可散列的,因此出现了错误。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值