【发布时间】:2016-08-18 07:11:53
【问题描述】:
我正在尝试查找给定句子中名词短语的跨度(开始索引,结束索引)。下面是提取名词短语的代码
sent=nltk.word_tokenize(a)
sent_pos=nltk.pos_tag(sent)
grammar = r"""
NBAR:
{<NN.*|JJ>*<NN.*>} # Nouns and Adjectives, terminated with Nouns
NP:
{<NBAR>}
{<NBAR><IN><NBAR>} # Above, connected with in/of/etc...
VP:
{<VBD><PP>?}
{<VBZ><PP>?}
{<VB><PP>?}
{<VBN><PP>?}
{<VBG><PP>?}
{<VBP><PP>?}
"""
cp = nltk.RegexpParser(grammar)
result = cp.parse(sent_pos)
nounPhrases = []
for subtree in result.subtrees(filter=lambda t: t.label() == 'NP'):
np = ''
for x in subtree.leaves():
np = np + ' ' + x[0]
nounPhrases.append(np.strip())
对于 a = "美国内战,也称为美国内战或简称内战,是在几个南方奴隶州宣布分离后,于 1861 年至 1865 年在美国爆发的内战并形成了美利坚联盟国。”,提取的名词短语是
['美国内战', '战争', '州', '内战', '内战战斗', '美国', '几个南方', '州', '分裂国家', '同盟国','美国']。
现在我需要找到名词短语的跨度(短语的开始位置和结束位置)。例如,上述名词短语的跨度将是
[(1,3), (9,9), (12, 12), (16, 17), (21, 23), ....].
我对 NLTK 还很陌生,我研究过 http://www.nltk.org/_modules/nltk/tree.html。我尝试使用 Tree.treepositions() 但无法使用这些索引提取绝对位置。任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: python tree nlp nltk chunking