使用Regex查找实体(以大写或数字开头)

2024-04-20 04:03:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面给出的文本,我试图从文本中提取有意义的信息(以大写字母或数字开头的术语)

The text is : "My name is Sam Helsen or Sam H Helsen son of M Helsen working at 3M technologies as the President of Sales"

我试图提取的信息在上述列表中给出:

info = ["My",'Sam Helsen', 'Sam H Helsen', 'M Helsen', '3M', 'President of Sales'

我使用了下面的正则表达式,它从上面的列表中提取了一些信息,但不是全部。你知道吗

Regex : re.findall(r'\b[A-Z1-9][\d\w]+(?:[\'\s-]\b[A-Z]\w+)*', sent, re.DOTALL)
Output: ['Sam Helsen', 'Sam', 'Helsen', 'Helsen', '3M', 'President', 'Sale']

通过查看regex,我明白了为什么我无法获取所有信息,但是当我修改regex时,它会更改其他输出。你知道吗

任何帮助都将不胜感激。你知道吗


Tags: of文本re信息列表ismysam
2条回答

你可以试试这个:

(?<!^|\n|[.!?] )[A-Z\d][A-Za-z\d]*(?: (?:of )?[A-Z\d][A-Za-z\d]*)*

demo。你知道吗


分解:

(?<!                     make sure this isn't the first word. Should not be preceded by...
   ^                     ...nothing
   |\n                   ...or a newline
   |[.!?] )              ...or another sentence
[A-Z\d][A-Za-z\d]*       match a word if it starts with a capital or a digit
(?:                      continue matching infinitely as long as...
    (?:of )?             ...the next word is "of" and/or...
   [A-Z\d][A-Za-z\d]*    ...the following word is capitalized
)*

不要真的明白你想做什么,但会尝试一下我的答案:

/\s(([0-9]?[A-Z]\w*)+((\sof)?\s?[0-9]?[A-Z]\w*)*)/g

\s-强制单词前面有空格,这样就不能是第一个

([0-9]?[A-Z]\w*)+-匹配首个单词,首字母为大写或数字

(\sof)?\s?-如果两个大写单词之间有一个或多个空格,则匹配连接符'of'

[0-9]?[A-Z]\w*)*-匹配后面可能出现的任何其他单词

http://regexr.com/3detv

相关问题 更多 >