-1

我正在尝试使用正则表达式捕获 Stanford CoreNLP 依赖解析器的输出。我想捕获跨越多行的依赖项解析(dependencies):和之间Sentence的所有内容。数据样本:

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 上试用它时,它工作正常。

非常感谢帮助

4

1 回答 1

0

使用re.findall(r"(?<=dependencies\):).*?(?=Sentence)", s, flags=re.DOTALLLookbehind & Lookahead

演示:

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']
于 2018-07-05T10:16:13.323 回答