如何从单词到句子结尾匹配?

时间:2019-04-29 04:27:11

标签: python regex python-3.x string

我想在python正则表达式python中加上“ is”一词后的整个句子。

尝试

s = '''Robert is an English actor, model and musician.
He started his film career by playing Cedric Diggory in Harry Potter.'''
r = re.findall(r'(?:is) (.*)',s)
print(r)

我希望输出为:

'an English actor, model and musician'

但是实际输出是:

['an English actor, model and musician','film career by playing Cedric Diggory in Harry Potter']

4 个答案:

答案 0 :(得分:1)

由于您只希望从is到句子结尾,this RegEx将起作用:

\bis\s+(.+?)\.

,它需要与标志s一起使用,以便.也与换行符匹配,以防句子分散在多行中。我将+.一起使用,因为.*会使整个正则表达式匹配,即使is.之间没有任何匹配,这对于句子。

enter image description here

.从输出中移出,将其移出捕获括号。 “句子的其余部分”在第一个捕获组中。

但是请注意,如果句子中有Mrs.之类的东西(并且有很多短语包含.可能属于一个句子),那么这种简单的方法就行不通了。

解析自然语言非常困难。如果你有 任何比简单,定义明确和可预测的文本都复杂的事情,那么您应该使用专用的库。快速搜索显示例如全面的库NLTKspaCy


This helpful regex tool提供了有关其匹配方式的说明。您尝试的变化

(\bis\b)([\s\S]*)

enter image description here

有关详细信息,请参见链接页面。评论

  • 它将创建两个捕获组,目标输出是第二个捕获组,您可以使用 $ 2 对其进行调用。

  • 第一组在您唯一的 is 实例周围创建单词边界。

  • 您可以使用 \ 转义任何语言特定的元字符。

答案 1 :(得分:1)

您需要在is周围使用单词边界,以便仅is可以匹配整个单词,而不能部分匹配其他单词,例如它与his匹配(这不是故意的),并且使用此正则表达式,

\bis\s+([^.]*)

在没有单词边界的情况下,甚至his也会匹配并为您提供您不想要的第二句话。

Regex Demo

尝试此修改后的Python代码,

import re

s = '''Robert is an English actor, model and musician.
He started his film career by playing Cedric Diggory in Harry Potter.'''
r = re.findall(r'\bis\s+([^.]*)',s)
print(r)

仅打印

['an English actor, model and musician']

答案 2 :(得分:0)

使用partition()可能会更容易:

splice = s.partition("is")[2]  # an English actor, model and musician. He started his film career by playing Cedric Diggory in Harry Potter.

然后split()

final = splice.split('.')[0]

答案 3 :(得分:-1)

之所以这样,是因为.*是贪婪的,如果可能(并且可以)匹配所有其余部分。

由于您具有新的行分隔符,因此可以根据需要使用它。 仅对该字符串使用正则表达式,您可以使用正向(?<=is)来做到这一点。 将匹配但不包含在结果中

s = '''Robert is an English actor, model and musician.
He started his film career by playing Cedric Diggory in Harry Potter.'''
r = re.findall(r'(?<=is).*\n',s)
print(r)
[' an English actor, model and musician.\n']
相关问题