3

我是该网站和 python 的新手,所以我希望我能提供所有必需的信息。我已经搜索过这个问题,但似乎没有一个解决方案对我有用。

我正在尝试创建一个函数来读取一些文本并返回它包含的数字数量。例如:

"It is 2012" , 应该返回 "Text has 4 digits"

如果没有数字,它应该返回不同的消息,例如:

"今天是星期一" ,应该返回 "文本不包含数字"

所以我写了这个:

def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit() == False:
            print ("Text does not contain digits")

        else:
            sum += 1


    print("Text has", sum, "digit(s)")


txt = str(input("Write some text: "))
(CountNumbers(txt))

功能似乎没问题,但是打印结果错误,例如:

Write some text: 65
Text has 2 digit(s) #this is ok, but...

当我只输入文本时:

Write some text: sd 
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 0 digit(s)

当我输入文本和数字(但首先输入文本)时:

Write some text: sd 564
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 3 digit(s)

我知道我的错误在于块,(我认为),但我还没有想出办法,因为当我使用返回时,它会在完成阅读文本之前停止。我已经尝试了大约 20 多种不同的东西,请帮助我!

谢谢 !!

PS 我需要它作为 .py 而不仅仅是在 IDLE (Python Shell) 窗口中工作,这就是为什么我要编写这样的块。

4

4 回答 4

4

问题是您每次遇到非数字字符时都会打印“文本不包含数字”消息。当您知道有多少个字符时,请尝试将该 print 语句移到循环之后:

def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit():
            sum += 1

    if sum > 0:   
        print("Text has", sum, "digit(s)")
    else:
        print ("Text does not contain digits")

txt = str(input("Write some text: "))
(CountNumbers(txt))

编辑:关于好的 Python 代码还有几点:

  • 正如您问题的评论中所指出的,按照惯例,Python 中的函数/方法用下划线小写命名,即count_numbersnot CountNumbers
  • Pedantic 模式:您正在计算字符串中的数字,而不是数字,因此为了清楚起见,它确实应该命名count_digits
  • 有一个名为sum的内置 Python 函数。通过使用同名变量来隐藏此函数被认为是不好的做法。我会将您的sum变量重命名为count.
  • 无需将函数调用括在括号中(它不会造成任何伤害,除了让它看起来很糟糕恕我直言)。

通过这些更改,您的代码变为:

def count_digits(txt):
    count = 0

    for n in txt:
        if n.isdigit():
            count += 1

    if count > 0:   
        print("Text has", count, "digit(s)")
    else:
        print ("Text does not contain digits")

txt = str(input("Write some text: "))
count_digits(txt)
于 2012-12-17T20:33:41.257 回答
2

我刚刚解决了你的代码问题:

def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit():
            sum += 1

    if sum:
        print("Text has", sum, "digit(s)")
    else:
        print ("Text does not contain digits")


CountNumbers(input("Write some text: "))
于 2012-12-17T20:33:38.190 回答
1

提前返回还不错,可以大大简化代码:

def CountNumbers(txt):
    for n in txt:
        if not n.isdigit():
            print ("Text does not contain digits")
            return

    print("Text has", len(txt), "digit(s)")

txt = str(input("Write some text: "))
(CountNumbers(txt))

此函数在出现非数字字符时立即返回,或打印输入字符串的长度(仅由数字组成)。

您也可以使用“生成表达式”来编写它,例如:

def CountNumbers(txt):
    if all(char.isdigit() for char in txt):
        print("Text has", len(txt), "digit(s)")
    else:
        print ("Text does not contain digits")

txt = str(input("Write some text: "))
(CountNumbers(txt))

现在,Python 函数更典型地返回值并让调用代码对其进行操作。此版本返回字符串并让程序的“主要”部分打印结果。它还将函数重命名为全小写(Python 通常使用大写的类名称):

def countnumbers(txt):
    if all(char.isdigit() for char in txt):
        return "Text has %d digit(s)" % len(txt)
    else:
        return "Text does not contain digits"

txt = str(input("Write some text: "))
print(countnumbers(txt))

嗯,不要太破旧!但是 Python 也有漂亮的条件表达式,比如:

def countnumbers(txt):
    return ("Text has %d digit(s)" % len(txt)
        if all(char.isdigit() for char in txt)
        else "Text does not contain digits")

txt = str(input("Write some text: "))
print(countnumbers(txt))

最后,也许你想把它做成一个合适的模块,以便其他代码可以使用它。像这样包装程序的交互部分,它只会在您像命令行脚本一样运行它时执行,但如果您将其作为模块导入则不会执行:

def countnumbers(txt):
    return ("Text has %d digit(s)" % len(txt)
        if all(char.isdigit() for char in txt)
        else "Text does not contain digits")

if __name__ == '__main__':
    txt = str(input("Write some text: "))
    print(countnumbers(txt))

如果我将该函数编写为生产系统的一部分,那将非常接近它的外观。请注意,逻辑与您的第一次尝试相同。最大的不同是这个版本让 Python 完成了大部分工作。

于 2012-12-17T21:18:19.633 回答
0

对原始版本进行了稍微 Pythonic 的改造。就个人而言,我发现“列表理解”形式更容易阅读(除非它是嵌套的):

def count_digits(txt):
    count = len([c for c in txt if c.isdigit()])

    if count > 0:
        print ("Text has", count, "digit(s)")
    else:
        print ("Text does not contain digits")
于 2012-12-17T21:31:38.827 回答