我试着用一个简单英语的用法例子来为一个单词的定义编写一个小的解析器。你知道吗
例如
我希望将上述两个示例分解为:
[('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.'
和''
?你知道吗
有一个更优雅的解决方案,但是您可以将可选元素转换为非捕获组(
?:
):密钥是
(?:e.?g.?|(?:for )
相关问题 更多 >
编程相关推荐