嗨,我在 NLTK3 中尝试此代码:- 我设法修复了第 6 行以与 NLTK 版本 3 一起使用。但 for 循环仍然不返回任何内容。
import nltk
sample = """ some random text content with names and countries etc"""
sentences = nltk.sent_tokenize(sample)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences=nltk.chunk.ne_chunk_sents(tagged_sentences) #Managed to fix this to work with version_3
for i in chunked_sentences:
if hasattr(i,'label'):
if i.label()=='NE':
print i
此外,如果我尝试调试,我会看到以下输出:
for i in chunked_sentences:
if hasattr(i,'label') and i.label:
print i.label
S
S
S
S
S
S
S
S
那么我如何检查它是否为“NE”。 NLTK-3 有问题,我真的无法弄清楚。请帮忙
最佳答案
您似乎正在迭代句子。我假设您想要迭代句子中包含的各个节点。
它应该像这样工作:
for sentence in chunked_sentences:
for token in sentence:
if hasattr(token,'label') and token.label() == 'NE':
print token
编辑:为了将来的引用,让我知道您正在迭代句子的事实只是句子的根节点通常标记为“S”。
关于python - 在 NLTK3 中遍历新 block 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212050/