与Stanza和CoreNLPClient提取名词短语

问题描述 投票:0回答:1

我正在尝试使用Stanza(使用Stanford 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')

[这里是一个句子的示例,我正在客户端中使用tregrex函数来获取所有名词短语。 Tregex函数在python中返回dict of dicts。因此,我需要先处理tregrex的输出,然后再将其传递给NLTK中的Tree.fromstring函数,以正确地提取名词短语作为字符串。

pattern = 'NP'
text = "Albert Einstein was a German-born theoretical physicist. He developed the theory of relativity."
matches = client.tregrex(text, pattern) ``

因此,我想出了方法stanza_phrases,该方法必须遍历作为dict of dicts输出的tregrex,并正确格式化NLTK中的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)

生成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

这是我的输出:

{'Albert Einstein', 'He', 'a German-born theoretical physicist', 'relativity',  'the theory', 'the theory of relativity'}

[有没有一种方法可以使我用更少的行数来提高代码效率(特别是stanza_phrasesextract_phrase方法)

python nlp stanford-nlp stanza
1个回答
0
投票
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")
© www.soinside.com 2019 - 2024. All rights reserved.