python - 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
有任何想法吗 ?非常感谢你的帮助。
解决方案
这些神秘的错误可能是使用旧的 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()
['宗教节日']
推荐阅读
- amazon-web-services - 如何从 .configuration 文件加载配置文件并根据角色 arn 承担角色?
- python - 无法打开需求文件:[Errno 2] 没有这样的文件或目录:'requirements.txt'
- android - 使用 BottomNavigationView 时如何仅显示片段区域?
- python - Pygame只显示黑屏
- tensorflow - 在 tensorflow 2.3.0 的模型训练期间,详细输出中的这个批次是什么?
- algorithm - 计算多个集合中的所有无序对
- python - Python SQLAlchemy - TypeError:“类型”和“datetime.datetime”实例之间不支持“>”
- r - 变量的计数频率取决于 R 数据帧中的其他变量
- python - 如何向 model.decision_function 添加阈值?
- python - 康威在 Python 中的生命游戏的问题