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

在python中,如何从具有特定条件的句子中提取数字?,python,regex,Python,Regex,下面是我输入句子的一个例子。我想从以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'] 然后我试着在没有条件的情况下提取数字 pr

下面是我输入句子的一个例子。我想从以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']

不重复,因为我也在寻找cm,mm加浮点数的方法。

您可以使用带有
re.findall的前瞻:

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' 
result = re.findall(r'[\dx\.]+(?=\scm)', sen)
输出:

['1.9x1.4x2.0']
试试这个:

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']
['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)
输出:

输出
您可以使用3个捕获组来获取数字,并确保测量以
cm
mm
结束

输出

[('1.9', '1.4', '2.0')]
['1.9x1.4x2.0']
要获得包含
x
的输出,可以使用

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

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

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

数字不包括
x
可能的重复,我想知道为什么这不适用于“其他两个定义不清的小磨玻璃损伤,分别测量4.0 mm和3 mm”这样的句子您能帮忙吗?@pari如果您还想匹配该格式,您可以将包含
x
的第一部分作为可选部分<代码>(?看到了,你建议我删除“x”吗在第二步中,或者我可以写一些东西,在一步中提取以mm或cm结尾的数字并删除“x”吗?@pari,这取决于您想要匹配的内容。您可以像这样使所有部分可选,或者您可以将整个部分与
x
匹配,或者将单独的部分@pari匹配。您可以使用字符类to匹配1+空格或制表符。要仅获取值,您可以不使用组来匹配它们,并使用正向前瞻来断言cm或mm
\d+(?:\。\d+)(?:(?:x\d+(?:\。\d+)*)(?=[\t]+[cm]m)
[('1.9', '1.4', '2.0')]
(?<!\S)(\d+\.\d+x\d+\.\d+x\d+\.\d+) [cm]m(?!\S)
['1.9x1.4x2.0']
\d+(?:\.\d+)?(?:(?:x\d+(?:\.\d+)?)*)?(?=[ \t]+[cm]m)