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

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

什么好主意吗?


当前回答

这个怎么样?

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

其他回答

您可以使用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

更简单的解决方法是

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

我让@zyxue的回答更明确一点:

RE_D = re.compile('\d')

def has_digits(string):
    res = RE_D.search(string)
    return res is not None

has_digits('asdf1')
Out: True

has_digits('asdf')
Out: False

@zyxue在答案上提出的方案中,哪个是基准测试最快的方案?

您可以像这样使用str.isdigit函数使用任何函数

def has_numbers(inputString):
    return any(char.isdigit() for char in inputString)

has_numbers("I own 1 dog")
# True
has_numbers("I own no dog")
# False

或者你也可以使用正则表达式,就像这样

import re
def has_numbers(inputString):
    return bool(re.search(r'\d', inputString))

has_numbers("I own 1 dog")
# True
has_numbers("I own no dog")
# False