在python中,如何从具有特定条件的句子中提取数字?

2024-05-12 15:18:44 发布

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

这是我输入句子的一个例子。我想从以mm或cm结尾的句子中提取数字。这是我尝试制作的正则表达式。你知道吗

 sen = 'The study reveals a speculated nodule with pleural tagging at anterior basal segment of LLL, measured 1.9x1.4x2.0 cm in size' 

 re.findall(r'(\d+) cm',sen)

这将输出为

 ['0']

然后我试着无条件地提取数字

 print (re.findall('\d+', sen ))

这将输出为

 ['1', '9', '1', '4', '2', '0']

我的预期产出是

 ['1.9x1.4x2.0'] or ['1.9', '1.4', '2.0']

不重复,因为我也在寻找一种方法厘米,毫米加浮点数。你知道吗


Tags: therewith结尾cm数字例子句子
3条回答

您可以使用3个捕获组来获取数字,并确保使用character classcmmm结束测量。你知道吗

(?<!\S)(\d+\.\d+)x(\d+\.\d+)x(\d+\.\d+) [cm]m(?!\S)

部分

  • (?<!\S)负的lookback,断言直接在左边的不是非空格字符
  • (\d+\.\d+)x捕获第1组,匹配1+个数字和小数部分,然后 匹配x
  • (\d+\.\d+)x捕获第2组同上
  • (\d+.\d+) 捕获第3组匹配1+个数字和小数部分
  • [cm]m匹配cm或mm
  • (?!\S)负向前看,断言直接在左边的不是非空格字符

Regex demo| Python demo

例如

import re

regex = r"(?<!\S)(\d+\.\d+)x(\d+\.\d+)x(\d+\.\d+) [cm]m(?!\S)"
test_str = "The study reveals a speculated nodule with pleural tagging at anterior basal segment of LLL, measured 1.9x1.4x2.0 cm in size"

print(re.findall(regex, test_str))

输出

[('1.9', '1.4', '2.0')]

要获得包含x的输出,可以使用

(?<!\S)(\d+\.\d+x\d+\.\d+x\d+\.\d+) [cm]m(?!\S)

Regex demo| Python demo

输出

['1.9x1.4x2.0']

编辑

要仅匹配值并在数字和值之间允许1个或多个空格,可以使用正向先行:

\d+(?:\.\d+)?(?:(?:x\d+(?:\.\d+)?)*)?(?=[ \t]+[cm]m)

Regex

试试这个:

sen = 'The study reveals a speculated nodule with pleural tagging at anterior basal segment of LLL, measured 1.9x1.4x2.0 cm in size' 
import re
re.findall('\d+\.\d+', sen)

输出

['1.9', '1.4', '2.0']

另一种方法是:

import re
sen = 'The study reveals a speculated nodule with pleural tagging at anterior basal segment of LLL, measured 1.9x1.4x2.0 cm in size' 
output = re.findall('\d.\d', sen)

输出:

['1.9', '1.4', '2.0']

相关问题 更多 >