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

标签 python regex

这里有一句话“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/

相关文章:

Python 正则表达式不匹配行首

regex - Go 中不前瞻地匹配进行中的单词

python - Pivot 将行复制到新列 Pandas

python - 防止连接的套接字在 Python 中关闭

python - Pyqt:执行命令

python - 我们是否应该始终用列表理解替换 for 循环

Javascript正则表达式重复行匹配无法正常工作

Python排列递归

javascript - 如何调整我的正则表达式以仅替换缩写而不替换扩展?

c# - 顺序处理算法或正则表达式