Skip to main content
 首页 » 编程设计

python之如何从 tree.productions() 中提取元素

2024年10月25日12wayfarer

(1)我的目标:提取产生式的左侧和右侧。

(2)我的做法: 我正在使用斯坦福解析器和 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)我的问题是如何继续从每个 production 的两边提取元素,例如 'S' 和 'NP VP 。 '。有什么方法可以解决这个问题吗?

谁能帮助我并指出一些方向?

请您参考如下方法:

nltk.Tree 实际上是 Python list 的子类,所以你可以通过 访问任何节点 c 的 child 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 对象在任何情况下都作为键。