0

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

我做过类似的事情:

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'未定义的错误?

4

5 回答 5

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})
于 2012-11-06T11:59:01.683 回答
3
  • 在你的代码中,你的第一个 for 循环,你的letter.split()语句似乎没用。为什么要拆分单个字符,却进入循环?
  • 其次,你已经定义了你的f = dict()内部函数并在外面使用它。它不会在外面可见。
  • 第三,你不应该使用f.has_key. 只需执行此操作,key in my_dict即可检查 dict 中密钥的可用性。
  • 最后,您可以将字典作为参数传递给您的函数。然后在那里修改,最后返回。(尽管您也可以在不传递dict函数的情况下执行此操作。只需在那里创建一个新函数,然后返回它)。
  • 所以,在你的代码中,几乎一切都很好。f = dict()在调用它之前,您只需要删除函数中的第一个 for 循环,然后移到函数之外。并将其作为参数传递。

方式一:

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

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: -

或者,您也可以使用 中的预定义库函数Countercollections这正是您想要的。


方式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())
于 2012-11-06T12:02:39.357 回答
1
  1. f是在里面定义的get_letter_freq,你不能从外面访问它。
  2. 您的函数应该return构造字典。
  3. 您实际上应该调用该函数。
  4. 你对拆分一个字母有什么期望?把那部分放在外面,你就不需要内循环了。
于 2012-11-06T11:59:26.147 回答
0
import string
s="today the weather was really nice"
print dict([ ( letter, s.count(letter)) for letter in string.lowercase[:25]])

If case sensitivity is important use s.lower().count(letter) instead.

于 2012-11-06T12:36:07.960 回答
0

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

于 2012-11-06T11:59:52.843 回答