如何在字符串中搜索不同类型的数字

2024-04-25 07:17:04 发布

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

我有多个字符串,每个字符串包含一年和一些文本。一个字符串的例子是:"The year is 2004"。但是,另一个字符串可能类似于"this was made in 2003.5"。我如何检查许多这样的字符串并提取正确的数字?你知道吗


Tags: the字符串in文本is数字thisyear
3条回答

使用列表理解而不使用正则表达式

def convert(e):
    try:
        return float(e)
    except:
        return None

str = "the 1st year is 2004"
m = [e for e in str.split(" ") if len(e) >= 4 and convert(e)]
print m 
>>> ['2004']

正如其他人在不知道什么是“正确”数字的情况下提到的,很难给出适合所有用例的答案。然而,我假设这里的数字是4位数以上的

您可以在这里使用regex

>>> str = "The year is 2004"
>>> re.findall(r"[-+]?\d*\.\d+|\d+", str)
['2004']

>>> str = "this was made in 2003.5"
>>> re.findall(r"[-+]?\d*\.\d+|\d+", str)
['2003.5']

你可以使用正则表达式。例如,这将获得给定字符串中的所有数字:

>>> re.findall(r'\d+(?:\.\d+)?', 'year is 2004')
['2004']
>>> re.findall(r'\d+(?:\.\d+)?', 'this was made in 2003.5')
['2003.5']

您可以微调正则表达式以符合“正确”数字的定义。你知道吗

相关问题 更多 >