我如何通过 python 中的斯坦福解析器到达树的叶子



我通过执行以下操作在python中使用斯坦福解析器:

import os
sentence = "Did Matt win the men slalom?"
os.popen("echo '"+sentence+"' > ~/stanfordtemp.txt")
parser_out = os.popen("~/stanford-parser-2012-11-12/lexparser.sh  
  ~/stanfordtemp.txt").readlines()
for tree in parser_out:
    print tree

但是,我不知道如何访问解析器返回的树叶。你能帮我这个吗?我还必须编写一个能够从英语句子生成sql查询的代码。对此有什么提示吗?任何帮助将不胜感激。我也使用 nltk 来完成所有操作。

下面是一个构建树,然后递归构建叶子列表的示例。 示例文本取自在线斯坦福解析器。

# class for tree nodes
class Node:
    def __init__(self,start):
        self.start = start
        self.children = []
        self.text = ''
# make a tree        
def make_tree(s):
    stack = []
    nodes = []
    cur = None
    root = None    
    for i, c in enumerate(s):
        if c == '(':
            cur = Node(i)
            if stack:
                stack[-1].children.append(cur)
            stack.append(cur)
            if root is None:
                root = cur
        elif c == ')' and stack:
            topnode = stack.pop()
            text = s[topnode.start + 1: i]
            topnode.text = text
    return root
# list of leaves
def list_of_leaves(node):
    result = []
    for child in node.children:
        result.extend(list_of_leaves(child))
    if not result:
        return [node]
    return result
s = """(ROOT
  (SQ (VBD Did)
    (NP (NNP Matt))
    (VP (VB win)
      (NP (DT the) (NNS men) (NN slalom)))
    (. ?)))"""
root = make_tree(s)    
for node in list_of_leaves(root):
    print node.text

如何提取带有句子作为子树的单个子句?因此,每当一个子句开始(S,SBAR,SBARQ 等)时,提取为子树,直到遇到另一个子句。对于最后一句,它直到句子的结尾。

下面是一个示例:

(根 (S (S (NP (NNP John)) (副总裁(VBZ生活) (PP (英寸) (NP (NNP New) (NNP York) (NN city))))) (, ,) (抄送但是) (S (斯巴 (WHADVP (WRB 隨時)) (S (NP (PRP he)) (副总裁(VBZ旅行) (S (副总裁(至) (副总裁(VB工作))))) (, ,) (NP (PRP he)) (副总裁(VBZ旅行) (ADVP (RB 非常) (RB far)) (PP (至 至 ) (NP (PRP$ his) (NN work) (NN place))))) (. .)))

最新更新