字典理解的词频 [英] Word frequency with dictionary comprehension

查看:88
本文介绍了字典理解的词频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用字典来计算给定字符串上的单词频率.说:

I was trying to use a dictionary to count word frequency on a given string. Say:

s = 'I ate an apple a big apple'

我知道计算单词频率的最佳方法可能是使用collections.Counter.但是我想知道是否可以通过字典理解来解决这个问题.

I understand the best way to count word frequency is probably to use collections.Counter. But I want to know if I can solve this by using a dictionary comprehension.

我的原始方法(没有字典理解)是

My original method(without dictionary comprehension) was

dict = {}
for token in s.split(" "):
    dict[token] = dict.get(token, 0) + 1

它工作正常:

dict
{'I': 1, 'a': 1, 'an': 1, 'apple': 2, 'ate': 1, 'big': 1}

我试图对此使用字典理解,

I tried to use a dictionary comprehension to this, like

dict = {}
dict = {token: dict.get(token, 0) + 1 for token in s.split(" ")}

但这没用.

dict
{'I': 1, 'a': 1, 'an': 1, 'apple': 1, 'ate': 1, 'big': 1}

字典理解有什么问题?是因为我在理解中使用了自己,所以每次在理解中调用dict.get('apple', 0时,我都会得到0吗?但是,我不知道如何进行测试,因此我不确定100%.

What's wrong with the dictionary comprehension? Is it because I used itself inside the comprehension so every time I called dict.get('apple', 0) in the comprehension, I will get 0? However, I don't know how to test this so I am not 100% sure.

P.S.如果有什么不同,我正在使用python 3.

P.S. If it makes any difference, I am using python 3.

推荐答案

如果您逐个操作执行代码,就会发现问题所在.

If you go through your code operation by operation, you will see what is wrong.

首先,将dict设置为空字典. (如评论中所述,将它用作您自己的变量名是一个坏主意,但这不是问题所在.)

First you set dict to an empty dict. (As mentioned in the comments, it's a bad idea to use that for your own variable name, but that's not the problem here.)

第二,评估您的字典理解力.此时,名称dict仍指的是空字典.因此,每次执行dict.get(whatever, 0)时,它将始终获得默认值.

Secondly, your dict comprehension is evaluated. At this point the name dict still refers to the empty dict. So every time you do dict.get(whatever, 0), it will always get the default.

最后,将您填充的字典重新分配为名称dict,替换之前的空白.

Finally, your populated dict is reassigned to the name dict, replacing the empty one that was previously there.

这篇关于字典理解的词频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆