为字母创建字典

时间:2012-11-06 11:56:10

标签: python dictionary

我一直在尝试构建一个函数来从字符串中获取字母频率并将它们存储在字典中。

我做过类似的事情:

s="today the weather was really nice"

def get_letter_freq(s):
    for letter in(s):
        x=letter.split()
    f=dict()
    for each_letter in x:
        if f.has_key(x):
                   f[x]+=1
        else:
                    f[x]=1
print f

你能帮我把事情整理好并找出错误吗?

为什么我收到错误,我的'f'未定义?

5 个答案:

答案 0 :(得分:3)

除了缩进错误,您的程序还有许多其他问题,例如:

s = "today the weather was really nice"

def get_letter_freq(s):
    f = dict()
    for each_letter in s:      #you can directly iterate over a string, so no need of split()
        if each_letter in f:   #has_key() has been deprecated
            f[each_letter]+=1   
        else:
            f[each_letter]=1
    return f                 #better return the output from function

print get_letter_freq(s)

顺便说一句,collections.Counter()有助于此目的:

In [61]: from collections import Counter

In [62]: strs = "today the weather was really nice"

In [63]: Counter(strs)
Out[63]: Counter({' ': 5, 'e': 5, 'a': 4, 't': 3, 'h': 2, 'l': 2, 'r': 2, 'w': 2, 'y': 2, 'c': 1, 'd': 1, 'i': 1, 'o': 1, 'n': 1, 's': 1})

答案 1 :(得分:3)

  • 在你的代码中,你的第一个for循环,你有letter.split()语句似乎没用。为什么要拆分单个字符,进入循环?
  • 其次,您已在功能中定义了f = dict() 使用它ouside。它在外面不可见。
  • 第三,你不应该使用f.has_key。就这样做,key in my_dict来 检查dict中密钥的可用性。
  • 最后,您可以将字典作为参数传递给您 功能。然后在那里修改它,最后返回它。 (虽然您也可以在不通过函数中的dict的情况下执行此操作。只需在那里创建一个新的,然后返回它。)
  • 所以,在你的代码中,几乎一切都很好。您只需要在函数中删除第一个for循环,并在调用之前将f = dict()移到函数外部。并将其作为一个参数传递。

方式1:

因此,您可以尝试以下修改后的代码: -

def get_letter_freq(my_dict, s):
    for letter in s:
        if letter in my_dict:
            my_dict[letter] += 1
        else:
            my_dict[letter] = 1

    return my_dict

my_dict = dict()
my_str = "today the weather was really nice"
print get_letter_freq(my_dict, my_str)

方式2: -

或者,您也可以使用来自Counter的预定义库函数collections,它完全符合您的要求。


方式3: -

根据@thebjorn在评论中的建议,您还可以使用defaultdict,这将使您的工作更轻松,因为您不必检查key的可用性在添加它之前在字典中。计数将自动默认为0: -

from collections import defaultdict
def get_letter_freq(s):
    my_dict = defaultdict(int)

    for letter in s:
        my_dict[letter] += 1  

    return my_dict

my_str = "today the weather was really nice"
print list(get_letter_freq(my_str).items())

答案 2 :(得分:1)

  1. fget_letter_freq内定义,您无法从外部访问。
  2. 你的函数应return构造的字典。
  3. 你应该调用这个功能。
  4. 您对分割单个字母有何期待?只需将该部分保留,您就不需要内循环。

答案 3 :(得分:0)

print f需要缩进,如果它必须是get_letter_freq的一部分。 &安培; f在get_letter_freq之外不存在。因此错误。

答案 4 :(得分:0)

import string
s="today the weather was really nice"
print dict([ ( letter, s.count(letter)) for letter in string.lowercase[:25]])

如果区分大小写非常重要,请改用s.lower().count(letter)