首页 > 解决方案 > nltk 的 wordnet 中的 valueError

问题描述

我正在尝试计算一些中文单词的同义词。一切顺利,除了某些词。我的代码很简单,这里是:

from nltk.corpus import wordnet as wn
syn_list = wn.synsets(u'节日', lang='cmn')

这是错误信息:

File ".../python2.7/site-packages/nltk/corpus/reader/wordnet.py", line 1162, in of2ss
    return self.synset_from_pos_and_offset(of[-1], int(of[:8]))

File ".../python2.7/site-packages/nltk/corpus/reader/wordnet.py", line 1382, in synset_from_pos_and_offset
    synset = self._synset_from_pos_and_line(pos, data_file_line)

File ".../python2.7/site-packages/nltk/corpus/reader/wordnet.py", line 1512, in _synset_from_pos_and_line
    sense_index = offsets.index(synset._offset)

ValueError: 5171145 is not in list

有任何想法吗 ?非常感谢你的帮助。

标签: pythonnltkwordnet

解决方案


这些神秘的错误可能是使用旧的 WNDB 格式的结果,该格式将条目放在文件中的某些字节偏移处。如果文件更改,则必须更新字节偏移量。

你可以试试Wn库(免责声明:我写的),它从较新的 WN-LMF 格式构建了一个 wordnet 数据库。首先,您需要下载 wordnets 并构建数据库。此步骤可能需要几分钟,但只需执行一次。

$ python -m pip install wn
$ python -m wn download cmnwn
python -m wn download cmnwn
Download [##############################] (1297104/1297104 bytes) Complete
Added cmnwn:1.3+omw (Chinese Open Wordnet)

然后你可以像 NLTK 一样使用它:

>>> import wn
>>> zh = wn.Wordnet(lang='zh')  # recommended to create a Wordnet object
>>> zh.synsets('节日')
[Synset('cmnwn-15183428-n'), Synset('cmnwn-15171146-n'), Synset('cmnwn-00517728-n')]
>>> zh.synsets('节日')[0].lemmas()
['假日', '公休日', '节日']

请注意,语言代码zh不是cmn. 此外,与 NLTK 的 Synsets 和 Lemmas 相比,Wn 具有 Synsets、Senses 和 Words 类。FAQ可以解释一下。

中文 wordnet 基于普林斯顿 WordNet 并依赖它来建立关系(如上位词、下位词等)。如果要遍历关系,则需要安装 Princeton Wordnet ( pwn) 或更新的英语 WordNet ( ewn)。您可以像上面那样从命令行安装它,也可以从 Python 中安装它:

>>> zh.synsets('节日')[0].hyponyms()
[]
>>> wn.download('ewn:2020')
Download [##############################] (13643357/13643357 bytes) Complete
Added ewn:2020 (English WordNet)
>>> zh = wn.Wordnet(lang='zh', expand='ewn:2020')  # recreate zh with expanded relations
>>> len(zh.synsets('节日')[0].hyponyms())
8
>>> zh.synsets('节日')[0].hyponyms()[0].lemmas()
['宗教节日']


推荐阅读