1.问题/需求

在含有多行文字的英文段落或一篇英文中查找匹配含有关键字的句子。

例如在以下字符串:

text = '''Today I registered my personal blog in the cnblogs and wrote my first essay.
The main problem of this essay is to use python regular expression matching to filter out 
sentences containing keywords in the paper. To solve this problem, I made many attempts 
and finally found a regular expression matching method that could meet the requirements 
through testing. So I've documented the problem and the solution in this blog post and 
shared it for reference to others who are having the same problem. At the same time, 
this text is also used to test the feasibility of this matching approach. Some additional 
related thoughts and ideas will be added to this blog later.'''

中匹配含有’blog‘的句子。

2.解决方法

因为要找出所有含有关键字的句子,所以这里采用re库中findall()方法。同时,由于所搜索的字符串中含有换行符'\n',因此向re.compilel()传入re.DOTALL参数,以使'.'字符能够匹配所有字符,包括换行符'\n'。这样我们匹配创建Pattern对象为:

newre = re.compile('[A-Z][^.]*blog[^.]*[.]', re.DOTALL)
newre.findall(text) # 进行匹配
# 结果为:
['Today I registered my personal blog in the cnblogs and wrote my first essay.',
"So I've documented the problem and the solution in this blog post and \nshared it for reference to others who are having the same problem.",
'Some additional \nrelated thoughts and ideas will be added to this blog later.'] # 这其中的'\n'就是换行符, 它在字符串中是不显示的, 但是匹配结果中又显示出来了
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。