(1)我的目标:提取产生式的左侧和右侧。
(2)我的做法: 我正在使用 stanford parser 和 nltk 工具来提取句子的解析树。我的代码如下:
corenlp_dir = "/home/corenlp-python/stanford-corenlp-full-2013-11-12/"
parser = corenlp.StanfordCoreNLP(corenlp_path=corenlp_dir)
result_json = json.loads(parser.parse("I have a tree."))
for sentence in result_json["sentences"]:
t = Tree.fromstring(sentence["parsetree"])
print t.productions() # [ROOT -> S, S -> NP VP ., NP -> PRP, PRP -> 'I', VP -> VBP NP, VBP -> 'have', NP -> DT NN, DT -> 'a', NN -> 'tree', . -> '.']
print t.productions()[1] # S -> NP VP .
print type(productions()[1]) # <class 'nltk.grammar.Production'>
for (i,child) in enumerate(t):
print (i,child) # (0, Tree('S', [Tree('NP', [Tree('PRP', ['I'])]), Tree('VP', [Tree('VBP', ['have']), Tree('NP', [Tree('DT', ['a']), Tree('NN', ['tree'])])]), Tree('.', ['.'])])) I can only get one tree.
(3)我的问题是如何继续从每个 产生式 的两侧提取元素,例如 'S' 和 'NP VP 。 '。有什么方法可以解决这个问题吗?
有人可以帮助我并指出一些方向吗?
最佳答案
nltk.Tree
实际上是 Python list
的子类,因此您可以通过 访问任何节点
、c
的子节点c[0]c[1]
、c[2]
等。请注意,NLTK 树在设计上并不是显式二元的,因此您的概念“左”和“右”可能必须在契约(Contract)中的某个地方强制执行。
假设树是二叉树,您可以使用 c[0]
访问节点的左子节点,使用 c[1]
访问节点的右子节点。对于您的第二个任务:
But what I want to do is to extract the left-hand side of a production and gather right-hand side of all productions with the same left-hand side.
如果我理解正确,您可以遍历树并构建一个dict
,其中键位于左侧,值是可能的右侧产生式的列表。我不确定 nltk.Tree 对象是否可散列/不可变(如果不是,它们将不能用作 dict 键),但您可以使用字符串形式在任何情况下,Tree
对象都作为键。
关于python - 如何从 tree.products() 中提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676164/