Skip to main content
 首页 » 编程设计

python之如何通过python从句子中提取数字

2025年05月04日25lautakyan007

这里有一句话“A building is 100 m tall and 20 m wide”我想提取高度为100的数字,所以我使用

question = input "  " 
height = re.findall(r'(\d+) m tall', question) 

但是,有时句子不是“100 m tall”,而是“100 m high”。在这种情况下,我的程序无法再提取我想要的号码。有没有办法改进我的程序并让它工作,无论句子包含“高”还是“高”。

请您参考如下方法:

您可以通过|检查“高或高”条件:

(\d+) m (tall|high) 

演示:

>>> re.findall(r'(\d+) m (tall|high)', 'a building is 100 m tall and 20 m wide') 
[('100', 'tall')] 
>>> re.findall(r'(\d+) m (tall|high)', 'a building is 100 m high and 20 m wide') 
[('100', 'high')] 

如果您不想捕获单词,请使用非捕获组:

(\d+) m (?:tall|high)