Skip to main content
 首页 » 编程设计

python之在 NLTK3 中遍历 ne block 的问题

2024年10月25日10lhb25

您好,我正在 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”。