TGREP2搜索NLTK树
nltk_tgrep的Python项目详细描述
ntlk树的tgrep搜索实现。
版权所有(c)2013年3月16日Will Roberts<;wildwilhelm@gmail.com>;。
在麻省理工学院许可下授权(详细信息请参见源文件tgrep.py)。
此模块支持用于匹配NLTK树部分的TGREP2语法。 注意,这里实现的许多tgrep运算符都需要树 传递为ParentedTree。
TGREP教程: http://www.stanford.edu/dept/linguistics/corpora/cas-tut-tgrep.html
TGREP2手册: http://tedlab.mit.edu/~dr/Tgrep2/tgrep2.pdf
TGREP2来源: http://tedlab.mit.edu/~dr/Tgrep2/
用法:
>>> from nltk.tree import ParentedTree >>> import nltk_tgrep >>> tree = ParentedTree.fromstring('(S (NP (DT the) (JJ big) (NN dog)) (VP bit) (NP (DT a) (NN cat)))') >>> nltk_tgrep.tgrep_nodes(tree, 'NN') [ParentedTree('NN', ['dog']), ParentedTree('NN', ['cat'])] >>> nltk_tgrep.tgrep_positions(tree, 'NN') [(0, 2), (2, 1)] >>> nltk_tgrep.tgrep_nodes(tree, 'DT') [ParentedTree('DT', ['the']), ParentedTree('DT', ['a'])] >>> nltk_tgrep.tgrep_nodes(tree, 'DT $ JJ') [ParentedTree('DT', ['the'])]
这个实现增加了基于nltk选择节点的语法 树的位置。此语法是N加上表示 树的位置。例如,N(),N(0,),N(0,0)是 有效的节点选择器。示例:
>>> tree = ParentedTree.fromstring('(S (NP (DT the) (JJ big) (NN dog)) (VP bit) (NP (DT a) (NN cat)))') >>> tree[0,0] ParentedTree('DT', ['the']) >>> tree[0,0].treeposition() (0, 0) >>> nltk_tgrep.tgrep_nodes(tree, 'N(0,0)') [ParentedTree('DT', ['the'])]
注意事项:
- 链接修饰符:“?“”和“=”未实现。
- tgrep兼容性:使用“@”表示“!“,”{“代表”<;“,”}“代表”>;“是 未实施。
- “=”和“~”链接未实现。
已知问题:
涉及叶节点的链接关系存在一些问题 (在nltk树中表示为裸字符串)。为了 例如,考虑树:
(S (A x))
搜索字符串* !>> S应选择所有不 以某种方式被S节点(即 不是S的后代。显然,在这棵树中,唯一的节点 满足此条件的是顶部节点(因为它不是 被任何事物支配)。但是,这里的代码将发现 顶部节点和叶节点x。这是因为我们无法恢复 叶的父级,因为它存储为裸字符串。
在执行这种搜索时,可能的解决方法是 过滤掉所有叶节点。