python - 如何从 tree.products() 中提取元素

标签 python nlp nltk stanford-nlp context-free-grammar

(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/

相关文章:

Python分析图像中的特定区域

python - 通过给出不是当前日期的引用日期作为参数来从文本中提取日期

java - 使用 NLP 识别名词短语上的多个命名实体类型

python - 将文档分类

python - 如何在Python中读取多个nltk语料库文件并写入单个文本文件

python - 如何使用 nltk.Regexp.parser() 解析自定义标签

实现数据类型的 Pythonic 方式(Python 2.7)

使用 DAL 的 python app engine restful 服务

python - 按条件替换 pandas 数据框列中的值

nlp - TF-IDF 和余弦相似度的替代方案(比较不同格式的文档)