我试图从number旁边的值下面的文本和介于两者之间的文本中提取.

Text:
The conditions are: number 1, the patient is allergic to dust, number next, the patient has bronchitis, number 4, The patient heart rate is high.

从本文中,我想提取以下值:

  • 1, the patient is allergic to dust,
  • next, the patient has bronchitis,
  • 4, The patient heart rate is high

我有一个模式,可以得到number和句子第一个单词旁边的值:

(numbers? (\d+|next)[,.]?\s?(\w+))

这是使用re.findall的结果

[('number 1, the', '1', 'the'),
 ('number next, the', 'next', 'the'),
 ('number 4, The', '4', 'The')]

如你所见,使用组,我可以从文本中提取数字或next值.但我无法提取整个句子.

推荐答案

由于数字或next后面的.,以及空格字符是可选的,因此可以使用非贪心点在字符串的右侧或末尾再次断言数字来编写模式.

\bnumbers? (\d+|next)[,.]?\s?(\w.*?)(?= numbers?\b|\.?$)

Regex demo

import re
 
pattern = r"\bnumbers? (\d+|next)[,.]?\s?(\w.*?)(?= numbers?\b|\.?$)"
 
s = "The conditions are: number 1, the patient is allergic to dust, number next, the patient has bronchitis, number 4, The patient heart rate is high."
 
print(re.findall(pattern, s))

输出

[
    ('1', 'the patient is allergic to dust,'),
    ('next', 'the patient has bronchitis,'),
    ('4', 'The patient heart rate is high')
]

Python-3.x相关问答推荐

如何使用regex将电话号码和姓名从文本字符串中分离出来

使用递归将int转换为字符串

正确的本地react 方式-Django身份验证

如何在 python 中将带有时区信息的时间戳转换为 utc 时间

隐藏Cartopy中高纬度非矩形投影的右侧轴(纬度)标签

Django - ValueError:无法将字符串转换为浮点数:''

包含值超出范围的 ID 的新 DataFrame 列?

python2和python3中的列表生成器

从日志(log)文件中查找延迟最低的用户

spinbutton调整up/down箭头

你如何表达一个没有参数的 Python Callable?

python中是否有大于但小于函数?

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

Python3 的超级和理解-> TypeError?

通过多个键对字典列表进行分组和聚合

TypeError: write() 参数必须是 str,而不是字节(Python 3 vs Python 2)

如何为 anaconda python3 安装 gi 模块?

Django Rest 框架 ListField 和 DictField

TypeError:无法实例化类型元组;使用 tuple() 代替

字典理解中的操作顺序