Python正则表达式不起作用

Python正则表达式不起作用,python,regex,Python,Regex,我有一个关于正则表达式模式的问题。我必须写一个函数,在这里我必须找到以某个单词开头的句子,并且有一定数量的单词。这是我到目前为止写的: def sentences_starting_with(w,2(how many words has to contain the sentence),corpus(a text where to find the sentences)): upper=w[0].upper() repetition=length-1 pattern=u

我有一个关于正则表达式模式的问题。我必须写一个函数,在这里我必须找到以某个单词开头的句子,并且有一定数量的单词。这是我到目前为止写的:

def sentences_starting_with(w,2(how many words has to contain the sentence),corpus(a text where to find the sentences)):
    upper=w[0].upper()
    repetition=length-1

    pattern=upper+w[1:]+'(\s\w*){2}'


    return re.findall(pattern,corpus)
但问题是,当我把括号放在我必须重复的部分:(\s\w*){2}它不起作用。它只是给我一个列表,我在随机句子句子中间只有一个随机词,甚至连句子应该开始的单词也没有。
你能告诉我我做错了什么吗。谢谢:)

为了使该功能正常工作,我将第一行更改为:

def sentences_starting_with(w,corpus,length=2):
我使用了以下数据和函数调用:

corpus='For example, This starts a sentence and This will do another one. this one, however\
will not, because we are looking for the word "This" with a capital letter.'
sentences_starting_with("this", corpus)
pattern=upper+w[1:][+'(\s\w*){2}'
的值是
This(\s\w*){2}
,这意味着它与单词
This
匹配,后跟
(\s\w*){2}
(两个单词)。
\s\w*
周围的括号将捕获捕获的两个单词中的最后一个(第二个),包括前面的空格——意思是第三个单词,从
开始计算:

[' a', ' do']
我在整个模式周围添加了括号:

pattern='('+upper+w[1:]+'(\s\w*){2})'
现在模式是:
(This(\s\w*){2})
,它有两组括号。第一个包含整个模式,因此它将捕获整个匹配(单词
This
和下面的两个单词),而第二个将捕获第三个单词(前面有空格),返回:

[('This starts a', ' a'), ('This will do', ' do')]
然后,您可以循环浏览此列表,并获取每个元组的第一个元组

为了简化代码,您还可以在不想捕获的组的
)后面添加
?:
,例如,
(?:\s\w*)
。现在代码是:

pattern='('+upper+w[1:]+'(?:\s\w*){2})'
它返回:

['This starts a', 'This will do']

此外,这不是一个好的做法:

upper=w[0].upper()
在这种情况下,没有问题,因为函数
upper()
string
类中的一个方法

len = len(w)
这可能会进一步导致问题,因为函数
len
不再可访问。名称
len
现在指的是变量
len

在本例中:

w = 'Some random text'
name='monty python'
len = len(w)
print(len)
len2 = len(name)
输出将是:

16
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-349-9ef3e2e1cb59> in <module>
      6 len = len(w)
      7 print(len)
----> 8 len2 = len(name)

TypeError: 'int' object is not callable
16
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
6透镜=透镜(w)
7打印(len)
---->8 len2=len(名称)
TypeError:“int”对象不可调用

如果有捕获组,则只返回捕获组。如果要完整匹配,可能需要使用非捕获组:
(?:\s\w*){2}
如果我将你的代码塞进我的IDE,我会收到很多错误。请提供一个与你的问题相同的解调数据。谢谢。加载项:你的解调数据应该涵盖正则表达式的所有情况:肯定和否定。再次感谢。对于注释,请使用
\这是一个注释
或docstring来描述你的函数。添加你的函数call也是。理想情况下,您的问题运行时没有错误,我们只需要修改正则表达式。