如何从python中的字符串中提取包含逗号的数字

1 python regex

我试图找到文本中的所有数字并将它们返回到浮点数列表中。

文中:

  • 逗号用于分隔千位
  • 多个连续的数字用逗号和空格分隔
  • 数字可以附加到单词上

我的代码似乎提取了用逗号和空格分隔的数字以及附加到单词的数字。但是,它提取以逗号分隔的数字作为单独的数字

text = "30feet is about 10metre but that's 1 rough estimate several numbers are like 2, 137, and 40 or something big numbers are like 2,137,040 or something"

list(map(int, re.findall('\d+', text)))
Run Code Online (Sandbox Code Playgroud)

下面的建议效果很好

不幸的是,下面的输出返回一个字符串:

nums = re.findall(r'\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)', text)
print(nums)
Run Code Online (Sandbox Code Playgroud)

我需要将输出作为浮点数列表返回,中间有逗号,但没有语音标记。

Eg. 
extract_numbers("1, 2, 3, un pasito pa'lante Maria")
    is [1.0, 2.0, 3.0]
Run Code Online (Sandbox Code Playgroud)

不幸的是,我的尝试还没有成功。目前,我的代码读取

def extract_numbers(text):
  nums = re.findall(r'\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)', text)
  
    return (("[{0}]".format( 
                       ', '.join(map(str, nums))))) 

extract_numbers(TEXT_SAMPLE)
Run Code Online (Sandbox Code Playgroud)

Tim*_*sen 5

您可以尝试re.findall对以下模式进行正则表达式搜索:

\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)
Run Code Online (Sandbox Code Playgroud)

示例脚本 -在这里尝试

import re

text = "30feet is about 10metre but that's 1 rough estimate several numbers are like 2, 137, and 40 or something big numbers are like 2,137,040 or something"

nums = re.findall(r'\b\d{1,3}(?:,\d{3})*(?:\.\d+)?(?!\d)', text)
print(nums)
Run Code Online (Sandbox Code Playgroud)

这打印:

['30', '10', '1', '2', '137', '40', '2,137,040']
Run Code Online (Sandbox Code Playgroud)

这是正则表达式模式的解释:

\b            word boundary
\d{1,3}       match 1 to 3 leading digits
(?:,\d{3})*   followed by zero or more thousands terms
(?:\.\d+)?    match an optional decimal component
(?!\d)        assert the "end" of the number by checking for a following non digit
Run Code Online (Sandbox Code Playgroud)