我的功能缺失了什么? (蟒蛇)

时间:2014-04-09 00:49:45

标签: python python-2.7

我正在尝试创建一个函数,用于打印频率高于阈值的字符数...(n需要是一个非负数)

import urllib
txt = urllib.urlopen("http://students.informatics.unimelb.edu.au/~ivow/info1dev/mywork/info1media/data/moby.txt").read()

tally = {}
for char in txt:
    if char in tally:
        tally[char] += 1
    else:
        tally[char] = 1

char = 'b'

def freq_threshold(n):
    if tally[char] > n:
        return tally[char]

freq_threshold(3)

我希望我的函数只返回char出现在文本中的次数的计数,只有当计数大于我的freq_threshold(n)时。目前,它什么都不返回..

1 个答案:

答案 0 :(得分:2)

该函数不返回任何内容,因为b的计数小于阈值。在这种情况下,默认情况下它将返回None。无论如何,你需要像这样打印返回的值

print freq_threshold(3)

但如果要显示计数大于阈值的所有字符,则需要像这样迭代字典

def freq_threshold(n):
    return [(char, tally[char]) for char in tally if tally[char] > n]

这将打印所有计数大于3的字符以及实际计数本身。

无论如何,解决问题的更好方法是使用collections.Counter并接受要检查的字符的数量以及参数,例如

import urllib, collections
txt = urllib.urlopen("http://www.blahblahblah.com").read()

tally = collections.Counter(txt)

def freq_threshold(char, n):
    if tally[char] > n:
        return tally[char]

print freq_threshold('b', 3)

注意:您需要指定urlopen来电中使用的协议。