我试图在nltk中使用ne_chunk和pos_tag对一个句子进行分块。
from nltk import tag
from nltk.tag import pos_tag
from nltk.tree import Tree
from nltk.chunk import ne_chunk
sentence = "Michael and John is reading a booklet in a library of Jakarta"
tagged_sent = pos_tag(sentence.split())
print_chunk = [chunk for chunk in ne_chunk(tagged_sent) if isinstance(chunk, Tree)]
print print_chunk
这就是结果:
[Tree('GPE', [('Michael', 'NNP')]), Tree('PERSON', [('John', 'NNP')]), Tree('GPE', [('Jakarta', 'NNP')])]
我的问题是,是否可以不包括pos_tag (如上面的NNP ),而只包括树'GPE',‘人’?什么叫“GPE”?
提前感谢
发布于 2017-05-29 09:33:35
命名实体块将为您提供一棵同时包含块和标记的树。你不能改变这一点,但你可以把标签拿出来。从你的tagged_sent
开始
chunks = nltk.ne_chunk(tagged_sent)
simple = []
for elt in chunks:
if isinstance(elt, Tree):
simple.append(Tree(elt.label(), [ word for word, tag in elt ]))
else:
simple.append( elt[0] )
如果只想要块,请在上面省略else:
子句。您可以修改代码以任意方式包装代码块。我使用nltk Tree
将更改保持在最低限度。注意,一些块由多个单词组成(尝试在示例中添加"New“),因此块的内容必须是一个列表,而不是一个元素。
PS。"GPE“代表”地缘政治实体“(显然是一个愚蠢的错误)。您可以在nltk书这里中看到“常用标记”的列表。
发布于 2017-05-29 10:37:50
使用标记对https://stackoverflow.com/a/31838373/610569上的代码进行轻微的修改很可能是您所需要的。
是否可以不包括pos_tag (如上面的NNP ),而只包括Tree 'GPE','PERSON'?
是的,只需遍历Tree =)参见如何遍历NLTK树对象?
>>> from nltk import Tree, pos_tag, ne_chunk
>>> sentence = "Michael and John is reading a booklet in a library of Jakarta"
>>> tagged_sent = ne_chunk(pos_tag(sentence.split()))
>>> tagged_sent
Tree('S', [Tree('GPE', [('Michael', 'NNP')]), ('and', 'CC'), Tree('PERSON', [('John', 'NNP')]), ('is', 'VBZ'), ('reading', 'VBG'), ('a', 'DT'), ('booklet', 'NN'), ('in', 'IN'), ('a', 'DT'), ('library', 'NN'), ('of', 'IN'), Tree('GPE', [('Jakarta', 'NNP')])])
>>> from nltk.sem.relextract import NE_CLASSES
>>> ace_tags = NE_CLASSES['ace']
>>> for node in tagged_sent:
... if type(node) == Tree and node.label() in ace_tags:
... words, tags = zip(*node.leaves())
... print node.label() + '\t' + ' '.join(words)
...
GPE Michael
PERSON John
GPE Jakarta
GPE是什么意思?
GPE的意思是“地缘政治实体”。
GPE
标记来自ACE数据集https://stackoverflow.com/questions/44237087
复制相似问题