Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我的功能缺失了什么?(python)_Python_Python 2.7 - Fatal编程技术网

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

我的功能缺失了什么?(python),python,python-2.7,Python,Python 2.7,我正在尝试创建一个函数,它可以打印频率高于阈值的字符数。。。(n需要是一个非负数) 我希望我的函数仅当计数大于我的频率阈值(n)时,才返回字符在文本中出现的次数计数。当前,它不返回任何内容。函数不返回任何内容,因为b的计数小于阈值。在这种情况下,默认情况下它将返回None。无论如何,您需要像这样打印返回的值 print freq_threshold(3) def freq_threshold(n): return [(char, tally[char]) for char in tal

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


我希望我的函数仅当计数大于我的频率阈值(n)时,才返回字符在文本中出现的次数计数。当前,它不返回任何内容。

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

print freq_threshold(3)
def freq_threshold(n):
    return [(char, tally[char]) for char in tally if tally[char] > n]
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)
但是如果要显示计数大于阈值的所有字符,则需要像这样迭代字典

print freq_threshold(3)
def freq_threshold(n):
    return [(char, tally[char]) for char in tally if tally[char] > n]
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)
这将打印计数大于3的所有字符以及实际计数本身

无论如何,解决问题的更好方法是使用
collections.Counter
并接受要检查的字符计数和参数,如下所示

print freq_threshold(3)
def freq_threshold(n):
    return [(char, tally[char]) for char in tally if tally[char] > n]
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
调用中使用的协议。

该函数通常不会返回任何内容,您应该在问题主体中解释您的确切问题。谢谢,我已经编辑了我的帖子。我知道有更简单的方法来完成我想要完成的事情,但是为什么我的功能没有返回一个数字呢?在我使用的URL中,b出现了9次…@ZoeIngrid我得到了
9
,您是否正在打印返回值,就像我在回答中显示的那样?