如何在Python中计算字符串中的数字、字母和空格数量?

46

我正在尝试创建一个函数来检测字符串中有多少位数、字母、空格和其他字符。

以下是我目前的代码:

def count(x):
    length = len(x)
    digit = 0
    letters = 0
    space = 0
    other = 0
    for i in x:
        if x[i].isalpha():
            letters += 1
        elif x[i].isnumeric():
            digit += 1
        elif x[i].isspace():
            space += 1
        else:
            other += 1
    return number,word,space,other

但它没有起作用:

>>> count(asdfkasdflasdfl222)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    count(asdfkasdflasdfl222)
NameError: name 'asdfkasdflasdfl222' is not defined

我的代码有什么问题,如何将其改进为更简单和精确的解决方案?


4
你的代码有哪些不应该出现的行为?它应该做什么?你的调查结果表明了这种差异的原因是什么? - jscs
1
这个问题既不是主题又是打字错误(你错过了一对引号,请参见此答案)(至少有一个MCVE...)| 并且同时提出多个问题(1:有什么问题,2:如何改进)。问题2大多基于意见,更适合[codereview.se]('14年codereview存在吗?)| - user202729
我认为这个问题被赞的唯一原因是因为这个答案(甚至没有解决错误(问题1),而是重写了代码以不再使用函数)可能对许多人有帮助。||| 这个问题在Meta上被链接到 - user202729
12个回答

136

这里有另一个选择:

s = 'some string'

numbers = sum(c.isdigit() for c in s)
letters = sum(c.isalpha() for c in s)
spaces  = sum(c.isspace() for c in s)
others  = len(s) - numbers - letters - spaces

1
@sundarnataraj 这是一个权衡。当然,它会在输入字符串上迭代3次,但我认为这样更容易阅读。 - Óscar López
19
当你将任务分开时,解决方案会更加简洁。干得好!为了使它更快,考虑使用*itertools.imap()*,像这样:numbers = sum(imap(str.isdigit, s))。在最初的调用之后,它将以C速度运行,没有纯Python步骤和没有方法查找。 - Raymond Hettinger
谢谢@ÓscarLópez,我同意True被视为1,但是我想知道numbers = sum(c.isdigit() for c in s)生成了哪个可迭代对象?因为sum(1)返回如下:
sum(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable
- Shubham S. Naik
如我所说:一个生成器表达式。请在文档中阅读相关内容。 - Óscar López
@ÓscarLópez 我会阅读关于“生成器表达式”的内容。非常感谢!! - Shubham S. Naik
显示剩余4条评论

10

以下代码将任何非数字字符替换为“”,使您可以通过len函数计算此类字符的数量。

import re
len(re.sub("[^0-9]", "", my_string))

按字母排序:

import re
len(re.sub("[^a-zA-Z]", "", my_string))

更多信息 - https://docs.python.org/3/library/re.html


3

不应该将x = []设置为您输入的参数。这会将一个空列表设置为参数。此外,请使用 Python 的for i in x语法,如下所示:

for i in x:
    if i.isalpha():
        letters+=1
    elif i.isnumeric():
        digit+=1
    elif i.isspace():
        space+=1
    else:
        other+=1

缩进是正确的(在复制到stackoverflow时出错了)。我使用x=[]的原因是为了让Python知道x是一个列表。如果我删除x=[],它会显示:>>> count(aasdfs1111xxx) Traceback (most recent call last): File "<pyshell#250>", line 1, in <module> count(aasdfs1111xxx) NameError: name 'aasdfs1111xxx'未定义 - ray

2
计算字符串中字母的数量:
```

要计算字符串中字母的数量:

```
def iinn():        # block for numeric strings
      
   b=(input("Enter numeric letter string "))

   if b.isdigit():
       print (f"you entered {b} numeric string" + "\n")
            
   else:
    
       letters = sum(c.isalpha() for c in b)
       print (f"in the string {b} are {letters} alphabetic letters")
       print("Try again...","\n")        
    
   while True:
       iinn()

一组数字字符串将以相反的顺序呈现:
numbers = sum(c.isdigit() for c in b)

1

# Write a Python program that accepts a string and calculate the number of digits 
# andletters.

    stre =input("enter the string-->")
    countl = 0
    countn = 0
    counto = 0
    for i in stre:
        if i.isalpha():
            countl += 1
        elif i.isdigit():
            countn += 1
        else:
            counto += 1
    print("The number of letters are --", countl)
    print("The number of numbers are --", countn)
    print("The number of characters are --", counto)

1
忽略您的“修改后代码”可能正确或不正确的任何其他部分,引起您在问题中引用的错误的问题是由于调用“count”函数时使用未定义变量所导致的,因为您没有将字符串引用起来。
  • count(thisisastring222) 查找名为thisisastring222的变量传递给名为count的函数。要使其正常工作,您必须先定义该变量(例如,使用thisisastring222 = "AStringWith1NumberInIt."),然后您的函数将使用存储在变量中的内容而不是变量名称。
  • count("thisisastring222") 将字符串"thisisastring222"硬编码到调用中,这意味着count函数将使用传递给它的确切字符串进行操作。

要修复对函数的调用,请在asdfkasdflasdfl222周围添加引号,将count(asdfkasdflasdfl222)更改为count("asdfkasdflasdfl222")

就实际问题“如何在Python中计算字符串的数字、字母和空格”而言,乍一看,“修订后的代码”的其余部分看起来都还可以,除了返回行没有返回你在代码的其余部分中使用的同一变量。 为了修复它,而不改变代码中的任何其他内容,请将numberword更改为digitletters,将return number,word,space,other更改为return digit,letters,space,other,或者更好的做法是 return (digit, letters, space, other)以匹配当前行为,同时使用更好的编码风格并明确返回的值类型(在此情况下为元组)。

1
如果您想要一个简单的解决方案,可以使用列表推导式,然后获取该列表的长度:
len([ch for ch in text if ch.isdigit()])

这同样适用于isalpha()的用法。

0

这段代码中有两个错误:

1)你应该删除这一行,因为它会将 x 重写为空列表:

x = []

2) 在第一个“if”语句中,您应该缩进“letter += 1”语句,如下所示:

if x[i].isalpha():
    letters += 1

嗨,如果我刪除了 x = [],那麼當我運行時就會出錯。它說我輸入的字符串“未定義”。 - ray
我通过注释掉 x = [] 来执行这段代码,它运行得很好。你的代码中还有一个错误,你需要使用 isdigit 而不是 isnumberic。在这里,我假设 count 函数是通过将字符串传递给 x 参数来调用的。例如:count("1233AASD 43")如果这不能解决你的问题,请告诉我。 - Abhishek Mittal

0

这是您调用时的错误。您正在使用参数(asdfkasdflasdfl222)调用代码,该参数被解释为变量。但是,您应该使用字符串"asdfkasdflasdfl222"来调用它。


0
def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接