正则表达式,用于用Examp解析纯英语中的定义

2024-05-17 19:40:43 发布

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

我试着用一个简单英语的用法例子来为一个单词的定义编写一个小的解析器。你知道吗

例如

  • 例1-“Foo:bar的同伴,例如,我有一个名为FooBar的类”
  • 例2-“Foo:The companion of bar例如我有一个名为FooBar的类”

我希望将上述两个示例分解为:

[('Foo', 'The companion of bar', 'I have class called FooBar')]

这是我目前掌握的密码

import re
EXAMPLE_REGEX = re.compile("(.*):(.*)(e.?g.?|(for )?example)(.*)")
print EXAMPLE_REGEX.findall('Foo: The companion of bar e.g. I have class called FooBar')

输出:[('Foo', ' The companion of bar ', 'e.g.', '', ' I have class called FooBar')]

如何避免输出中额外的'e.g.'''?你知道吗


Tags: ofthere用法fooexamplehavebar
1条回答
网友
1楼 · 发布于 2024-05-17 19:40:43

有一个更优雅的解决方案,但是您可以将可选元素转换为非捕获组(?:):

import re
EXAMPLE_REGEX = re.compile("(.*):(.*)(?:e.?g.?|(?:for )?example)(.*)")
print EXAMPLE_REGEX.findall('Foo: The companion of bar e.g. I have class called FooBar')

密钥是(?:e.?g.?|(?:for )

相关问题 更多 >