我发现的大多数问题都偏向于这样一个事实,即他们在数字中寻找字母,而我在我想要的无数字符串中寻找数字。 我需要输入一个字符串并检查它是否包含任何数字,以及它是否拒绝它。

函数isdigit()仅当所有字符都是数字时才返回True。我只是想看看用户是否输入了一个数字,比如“我有一只狗”之类的句子。

什么好主意吗?


当前回答

使用Python方法str.isalpha()。如果字符串中所有字符都是字母,并且至少有一个字符,则此函数返回True;否则返回False。

Python文档:https://docs.python.org/3/library/stdtypes.html#str.isalpha

其他回答

使用Python方法str.isalpha()。如果字符串中所有字符都是字母,并且至少有一个字符,则此函数返回True;否则返回False。

Python文档:https://docs.python.org/3/library/stdtypes.html#str.isalpha

您可以使用NLTK方法。

这将在文本中找到'1'和'One':

import nltk 

def existence_of_numeric_data(text):
    text=nltk.word_tokenize(text)
    pos = nltk.pos_tag(text)
    count = 0
    for i in range(len(pos)):
        word , pos_tag = pos[i]
        if pos_tag == 'CD':
            return True
    return False

existence_of_numeric_data('We are going out. Just five you and me.')

你可以使用range和count来检查一个数字在字符串中出现了多少次:

def count_digit(a):
    sum = 0
    for i in range(10):
        sum += a.count(str(i))
    return sum

ans = count_digit("apple3rh5")
print(ans)

#This print 2

这个怎么样?

import string

def containsNumber(line):
    res = False
    try:
        for val in line.split():
            if (float(val.strip(string.punctuation))):
                res = True
                break
    except ValueError:
        pass
    return res

containsNumber('234.12 a22') # returns True
containsNumber('234.12L a22') # returns False
containsNumber('234.12, a22') # returns True

更简单的解决方法是

s = '1dfss3sw235fsf7s'
count = 0
temp = list(s)
for item in temp:
    if(item.isdigit()):
        count = count + 1
    else:
        pass
print count