这里有一句话“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)
关于python - 如何通过python从句子中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41355325/