VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • Python正则表达式匹配一段英文中包含关键字的句子

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) # [A-Z]表示匹配句子开头的大写字母, [^.]表示不匹配'.'符号, [.]表示匹配句子结尾的'.'号
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'就是换行符, 它在字符串中是不显示的, 但是匹配结果中又显示出来了
复制代码

 这个正则表达式是能够匹配完整句子的,不用担心句子中间的大写字母会使句子只匹配一小部分。因为python的正则表达式默认是’贪心‘匹配的,即在有二义的情况下,它们会尽可能匹配最长的字符串。在这里的话就是完整的句子。非贪心匹配的话在分组后面加个'?'即可。


出处:https://www.cnblogs.com/blogLYP/p/17080272.html


相关教程