Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式Findall未按预期工作_Python_Regex_Findall - Fatal编程技术网

Python正则表达式Findall未按预期工作

Python正则表达式Findall未按预期工作,python,regex,findall,Python,Regex,Findall,我试图使用正则表达式捕获StanfordCorenlp依赖项解析器的输出。我想捕获跨多行的依赖项解析(在依赖项之间的所有内容):和句子。数据样本: Dependency Parse (enhanced plus plus dependencies): root(ROOT-0, imply-5) dobj(imply-5, what-1) aux(imply-5, does-2) det(man-4, the-3) nsubj(imply-5, man-4) advmod(mentions-8,

我试图使用正则表达式捕获StanfordCorenlp依赖项解析器的输出。我想捕获跨多行的依赖项解析(在
依赖项之间的所有内容):
句子。数据样本:

Dependency Parse (enhanced plus plus dependencies):
root(ROOT-0, imply-5)
dobj(imply-5, what-1)
aux(imply-5, does-2)
det(man-4, the-3)
nsubj(imply-5, man-4)
advmod(mentions-8, when-6)
nsubj(mentions-8, he-7)
advcl(imply-5, mentions-8)
det(papers-10, the-9)
dobj(mentions-8, papers-10)
nsubj(written-13, he-11)
aux(written-13, has-12)
acl:relcl(papers-10, written-13)

Sentence #1 (10 tokens):
我使用的代码是:

regex = re.compile('dependencies\):(.*)Sentence', re.DOTALL)
found = regex.findall(text)
当我运行时,代码匹配整个文本文档,而不仅仅是捕获组。当我在Regexr上试用它时,它工作得很好


使用
re.findall(r)(?感谢Rakesh,知道我的方法为什么不起作用吗?使用
findall
,如果需要获得重叠匹配,只需要使用lookarounds。
re.findall
只返回捕获的子字符串,所以使用
(?谢谢@WiktorStribiżew adding?to.*解决了这个问题奇怪!Rakesh的答案对我有效,但我的答案似乎对我无效:如果Rakesh的答案对你有效,唯一的问题是你的真实文档在
依赖项之后包含多个
句子
s):
你只需要得到最左边的
句子
s,因此你需要的是惰性匹配,
*?
。是的,我应该在问题中更明确地说明这一点。我没有意识到这在这个例子中是至关重要的:)
import re

s = """ Dependency Parse (enhanced plus plus dependencies):
root(ROOT-0, imply-5)
dobj(imply-5, what-1)
aux(imply-5, does-2)
det(man-4, the-3)
nsubj(imply-5, man-4)
advmod(mentions-8, when-6)
nsubj(mentions-8, he-7)
advcl(imply-5, mentions-8)
det(papers-10, the-9)
dobj(mentions-8, papers-10)
nsubj(written-13, he-11)
aux(written-13, has-12)
acl:relcl(papers-10, written-13)

Sentence #1 (10 tokens):"""

m = re.findall(r"(?<=dependencies\):).*?(?=Sentence)", s, flags=re.DOTALL)
print(m)
['\nroot(ROOT-0, imply-5)\ndobj(imply-5, what-1)\naux(imply-5, does-2)\ndet(man-4, the-3)\nnsubj(imply-5, man-4)\nadvmod(mentions-8, when-6)\nnsubj(mentions-8, he-7)\nadvcl(imply-5, mentions-8)\ndet(papers-10, the-9)\ndobj(mentions-8, papers-10)\nnsubj(written-13, he-11)\naux(written-13, has-12)\nacl:relcl(papers-10, written-13)\n\n']