【问题标题】:why is the code returning IndexError error in python when the synsets of the word exists当单词的同义词存在时,为什么代码在python中返回IndexError错误
【发布时间】:2013-03-31 08:39:14
【问题描述】:

我不明白为什么会收到此错误。请帮忙

>>> mylist = []
>>> file1 = open("medDict.txt", "r")
>>> for line in file1:
    from nltk.corpus import wordnet
    print line
    wordFromList2 = wordnet.synsets(line)[0]
    mylist.append(wordFromList2)


abnormal


Traceback (most recent call last):
  File "<pyshell#10>", line 4, in <module>
    wordFromList2 = wordnet.synsets(line)[0]
IndexError: list index out of range

medDict.txt 包含以下单词

abnormal
acne
ache
diarrhea
fever

【问题讨论】:

标签: python-2.7 nltk wordnet


【解决方案1】:

@Blender 关于word.synsets() 的空格敏感性是正确的。如果您需要访问任何具有自然语言空格synsets,Wordnet 使用下划线 _ 而不是。例如。如果您想找到类似 kick the bucket 的内容,您可以使用 wn.synsets("kick_the_bucket") 从 NLTK WN 界面访问同义词集

>>> from nltk.corpus import wordnet as wn
>>> wn.synsets('kick the bucket')
[]
>>> wn.synsets('kick_the_bucket')
[Synset('die.v.01')]

但是,请注意,有时 WordNet 会使用破折号而不是下划线对某些同义词集进行编码。例如。 9-11 可访问,但 9_11 不可访问。

>>> wn.synsets('9-11')
[Synset('9/11.n.01')]
>>> wn.synsets('9_11')
[]

现在解决您的代码问题。

1. 当您逐行读取文件时,您还读取了行中不可见但存在的\n。所以你需要改变这个:

>>> mylist = []
>>> file1 = open("medDict.txt", "r")

到这里:

>>> words_from_file = [i.strip() for i in open("medDict.txt", "r")]

2.我不太确定你是否真的想要wordnet.synsets(word)[0],这意味着你只是第一感觉,请注意它可能不是Most Frequent Sense (MFS)。所以不要这样做:

>>> wordFromList2 = wordnet.synsets(line)[0]
>>> mylist.append(wordFromList2)

我认为更合适的方法是使用set 代替然后update 设置

>>> list_of_synsets = set()
>>> for i in words_from_file:
>>>  list_of_synsets.update(wordnet.synsets(i))
>>> print list_of_synsets

【讨论】:

    【解决方案2】:

    word.synsets() 对空格敏感:

    >>> wordnet.synsets('abnormal')
        [Synset('abnormal.a.01'), Synset('abnormal.a.02'), Synset('abnormal.s.03')]
    >>> wordnet.synsets(' abnormal')
        []
    

    .strip() 行中的空格,然后再传入:

    wordFromList2 = wordnet.synsets(line.strip())[0]
    

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 2021-12-09
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      相关资源
      最近更新 更多