[英]Python locate words in nltk.tree
我试图建立一个nltk来获取单词的上下文。 我有两个句子
sentences=pd.DataFrame({"sentence": ["The weather was good so I went swimming", "Because of the good food we took desert"]})
我想找出“好”这个词是什么意思。 我的想法是对句子进行分块(来自此处的教程代码),然后查看单词“ good”和一个名词是否在同一节点中。 如果不是,则表示该名词之前或之后的名词。
首先,按照本教程中的说明构建块
from nltk.corpus import conll2000
test_sents = conll2000.chunked_sents('test.txt', chunk_types=['NP'])
train_sents = conll2000.chunked_sents('train.txt', chunk_types=['NP'])
class ChunkParser(nltk.ChunkParserI):
def __init__(self, train_sents):
train_data = [[(t,c) for w,t,c in nltk.chunk.tree2conlltags(sent)]
for sent in train_sents]
self.tagger = nltk.TrigramTagger(train_data)
def parse(self, sentence):
pos_tags = [pos for (word,pos) in sentence]
tagged_pos_tags = self.tagger.tag(pos_tags)
chunktags = [chunktag for (pos, chunktag) in tagged_pos_tags]
conlltags = [(word, pos, chunktag) for ((word,pos),chunktag)
in zip(sentence, chunktags)]
return nltk.chunk.conlltags2tree(conlltags)
NPChunker = ChunkParser(train_sents)
然后,将其应用到我的句子中:
sentence=sentences["sentence"][0]
tags=nltk.pos_tag(sentence.lower().split())
result = NPChunker.parse(tags)
print result
结果看起来像这样
(S
(NP the/DT weather/NN)
was/VBD
(NP good/JJ)
so/RB
(NP i/JJ)
went/VBD
swimming/VBG)
现在,我想“查找”单词“ good”在哪个节点上。 我还没有真正找到更好的方法,只是计算节点和叶子中的单词。 单词“ good”是句子中的单词3。
stuctured_sentence=[]
for n in range(len(result)):
stuctured_sentence.append(list(result[n]))
structure_length=[]
for n in result:
if isinstance(n, nltk.tree.Tree):
if n.label() == 'NP':
print n
structure_length.append(len(n))
else:
print str(n) +"is a leaf"
structure_length.append(1)
通过总结单词的数量,我知道单词“ good”在哪里。
structure_frame=pd.DataFrame({"structure": stuctured_sentence, "length": structure_length})
structure_frame["cumsum"]=structure_frame["length"].cumsum()
有没有更简单的方法来确定单词的节点或叶,并找出“好”一词指的是什么?
最佳亚历克斯
在叶子列表中找到单词最容易。 然后,您可以将叶子索引转换为树索引,这是树下的路径。 要查看将good
东西分组,请上一层并检查从中挑选出的子树。
首先,找出平淡句子中good
位置。 (如果您仍将未标记的句子作为标记列表,则可以跳过此步骤。)
words = [ w for w, t in result.leaves() ]
现在我们找到good
的线性位置,并转换为树路径:
>>> position = words.index("good")
>>> treeposition = result.leaf_treeposition(position)
>>> print(treeposition)
(2, 0)
“树位置”是沿着树的路径,表示为元组。 (NLTK树可以用元组和整数建立索引。)要查看good
的姐妹们,请在到达路径末端之前停止一步。
>>> print(result[ treeposition[:-1] ])
Tree('NP', [('good', 'JJ')])
你在这。 一棵只有一片叶子的子树,一对(good, JJ)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.