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

2024-06-28 19:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数来打印频率高于阈值的字符数。。。(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\u阈值(n)时。目前,它什么也不返回。。你知道吗


Tags: 函数inimporttxtthresholdif阈值urllib
1条回答
网友
1楼 · 发布于 2024-06-28 19:31:04

函数不返回任何内容,因为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调用中使用的协议。你知道吗

相关问题 更多 >