gpt4 book ai didi

python - NLTK树中叶子的绝对位置

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:42 25 4
gpt4 key购买 nike

我正在尝试查找给定句子中名词短语的跨度(开始索引、结束索引)。下面是提取名词短语的代码

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

For a = "美国内战,也称为州与州之间的 war 或简称内战,是 1861 年至 1865 年在美国南部几个蓄奴州宣布脱离联邦后发生的内战并成立了美利坚联盟国。",提取的名词短语是

['美国内战', ' war ', '州', '内战', '内战', '美国', '几个南方', '州', ' split 国家', “同盟国”、“美国”]。

现在我需要找到名词短语的跨度(短语的开始位置和结束位置)。例如,上述名词短语的跨度将是

[(1,3), (9,9), (12, 12), (16, 17), (21, 23), ....]

我是 NLTK 的新手,我研究过 http://www.nltk.org/_modules/nltk/tree.html .我尝试使用 Tree.treepositions() 但无法使用这些索引提取绝对位置。任何帮助将不胜感激。谢谢!

最佳答案

没有任何隐式函数返回 https://github.com/nltk/nltk/issues/1214 突出显示的字符串/标记的偏移量

但是您可以使用 RIBES score 使用的 ngram 搜索器来自 https://github.com/nltk/nltk/blob/develop/nltk/translate/ribes_score.py#L123

>>> from nltk import word_tokenize
>>> from nltk.translate.ribes_score import position_of_ngram
>>> s = word_tokenize("The American Civil War, also known as the War between the States or simply the Civil War, was a civil war fought from 1861 to 1865 in the United States after several Southern slave states declared their secession and formed the Confederate States of America.")
>>> position_of_ngram(tuple('American Civil War'.split()), s)
1
>>> position_of_ngram(tuple('Confederate States of America'.split()), s)
43

(它返回查询ngram的起始位置)

关于python - NLTK树中叶子的绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com