Jes*_*ABI 3 python nlp stanford-nlp stanford-stanza
我正在尝试使用 Stanza(使用斯坦福 CoreNLP)从句子中提取名词短语。这只能通过 Stanza 中的 CoreNLPClient 模块来完成。
# Import client module
from stanza.server import CoreNLPClient
# Construct a CoreNLPClient with some basic annotators, a memory allocation of 4GB, and port number 9001
client = CoreNLPClient(annotators=['tokenize','ssplit','pos','lemma','ner', 'parse'], memory='4G', endpoint='http://localhost:9001')
Run Code Online (Sandbox Code Playgroud)
这是一个句子的例子,我正在使用tregrex客户端中的函数来获取所有名词短语。Tregex函数dict of dicts在python中返回a 。因此,我需要先处理 的输出,tregrex然后再将其传递给Tree.fromstringNLTK 中的函数,以将名词短语正确提取为字符串。
pattern = 'NP'
text = "Albert Einstein was a German-born theoretical physicist. He developed the theory of relativity."
matches = client.tregrex(text, pattern) ``
Run Code Online (Sandbox Code Playgroud)
因此,我想出了一种方法stanza_phrases,它必须循环遍历NLTKdict of dicts的输出tregrex并正确格式化Tree.fromstring。
def stanza_phrases(matches):
Nps = []
for match in matches:
for items in matches['sentences']:
for keys,values in items.items():
s = '(ROOT\n'+ values['match']+')'
Nps.extend(extract_phrase(s, pattern))
return set(Nps)
Run Code Online (Sandbox Code Playgroud)
生成由 NLTK 使用的树
from nltk.tree import Tree
def extract_phrase(tree_str, label):
phrases = []
trees = Tree.fromstring(tree_str)
for tree in trees:
for subtree in tree.subtrees():
if subtree.label() == label:
t = subtree
t = ' '.join(t.leaves())
phrases.append(t)
return phrases
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
{'Albert Einstein', 'He', 'a German-born theoretical physicist', 'relativity', 'the theory', 'the theory of relativity'}
Run Code Online (Sandbox Code Playgroud)
有没有一种方法,我可以让这个更高效的代码用更少的线数(尤其是stanza_phrases和extract_phrase方法)
from stanza.server import CoreNLPClient
# get noun phrases with tregex
def noun_phrases(_client, _text, _annotators=None):
pattern = 'NP'
matches = _client.tregex(_text,pattern,annotators=_annotators)
print("\n".join(["\t"+sentence[match_id]['spanString'] for sentence in matches['sentences'] for match_id in sentence]))
# English example
with CoreNLPClient(timeout=30000, memory='16G') as client:
englishText = "Albert Einstein was a German-born theoretical physicist. He developed the theory of relativity."
print('---')
print(englishText)
noun_phrases(client,englishText,_annotators="tokenize,ssplit,pos,lemma,parse")
# French example
with CoreNLPClient(properties='french', timeout=30000, memory='16G') as client:
frenchText = "Je suis John."
print('---')
print(frenchText)
noun_phrases(client,frenchText,_annotators="tokenize,ssplit,mwt,pos,lemma,parse")
Run Code Online (Sandbox Code Playgroud)