Skip to main content
 首页 » 编程设计

python之NLTK ConllCorpusReader 中的 NE 标签

2025年01月19日14jackei

我正在尝试将 CoNLLCorpusReader 用于 CoNLL2003 数据集。该数据集包含 4 列(示例):

WORD      POS   CHUNK NE 
U.N.      NNP   I-NP  I-ORG 
official  NN    I-NP  O 
Ekeus     NNP   I-NP  I-PER 
heads     VBZ   I-VP  O 
for       IN    I-PP  O 
Baghdad   NNP   I-NP  I-LOC 
.         .     O     O 

我创建了语料库并且它有效 - 我可以使用 pos 标签和 block 标签获取单词、发送和元组。

问题是,如何从我的语料库中获取命名实体标签?我知道有 corpus.raw() 方法,但是真的没有办法用 corpus.iob_words() 之类的东西得到它吗?我发现了这个问题:https://github.com/nltk/nltk/issues/63 ,但是在这个 corpusReader 的最新版本中,iob_words 方法中没有额外的参数,我可以使用它来更改我想要获取的列列表。

请您参考如下方法:

看来得靠自己了。试一试,我认为您只需要扩展ConllCorpusReader 就可以告诉iob_words() 选择 NE 列而不是(默认)CHUNK 列。 iob_sents() chunked_words() 和 chunked_sents() 应该做类似的修改。

class betterConllReader(ConllCorpusReader): 
 
    def iob_words(self, fileids=None, tagset=None, column="chunk"): 
        """ 
        :return: a list of word/tag/IOB tuples 
        :rtype: list(tuple) 
        :param fileids: the list of fileids that make up this corpus 
        :type fileids: None or str or list 
        """ 
        self._require(self.WORDS, self.POS, self.CHUNK) 
        def get_iob_words(grid): 
            return self._get_iob_words(grid, tagset, column) 
        return LazyConcatenation(LazyMap(get_iob_words, self._grids(fileids))) 
 
    def _get_iob_words(self, grid, tagset=None, column="chunk"): 
        pos_tags = self._get_column(grid, self._colmap['pos']) 
        if tagset and tagset != self._tagset: 
            pos_tags = [map_tag(self._tagset, tagset, t) for t in pos_tags] 
        return list(zip(self._get_column(grid, self._colmap['words']), pos_tags, 
                   self._get_column(grid, self._colmap[column]))) 

我所做的只是用关键字参数替换硬编码的“chunk”。通过更多的工作,可以选择多个列(对于 iob_*() 是合理的,对于 chunked_*() 变体则不太清楚。)