【发布时间】:2019-02-06 00:51:55
【问题描述】:
我想对字符串进行分块以使组处于特定高度。应保留原始顺序,并且还应完整包含所有原始单词。
import nltk
height = 2
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"), ("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]
pattern = """NP: {<DT>?<JJ>*<NN>}
VBD: {<VBD>}
IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)
In [29]: Tree.fromstring(str(result)).pretty_print()
S
_________________|_____________________________
NP VBD IN NP
________|_________________ | | _____|____
the/DT little/JJ yellow/JJ dog/NN barked/VBD at/IN the/DT cat/NN
我的方法有点像下面这样的蛮力:
In [30]: [list(map(lambda x: x[0], _tree.leaves())) for _tree in result.subtrees(lambda x: x.height()==height)]
Out[30]: [['the', 'little', 'yellow', 'dog'], ['barked'], ['at'], ['the', 'cat']]
我认为应该存在一些直接的 API 或者我可以用来进行分块的东西。任何建议都受到高度赞赏。
【问题讨论】:
-
不。但只需致电
Tree.leaves()并检查Tree.height。你做对了 =) -
@alvas 没关系。但我不明白你提到这两种方法的意思。以及某人的反对票。 :)
-
不是我 ;P
-
@alvas 我认为保持字符串不仅不重叠和分组而且保持完整和原始顺序会更好。
-
那么你不仅想要 Tree 对象的叶子,还想要 Tree 或 str 的叶子?目前尚不清楚目的是什么。你能再提供几个输入/输出吗?
标签: python nlp nltk depth-first-search chunking