1

我正在尝试将 python 与 NTLK 一起使用来获取多个单词的多个首字母缩写词(目前为 2 个)。似乎我可以让它与第一个词一起工作,但不是第二个。我猜我还有很多关于 NTLK 的知识要学习。下面有一些简化的示例代码。我基本上是在尝试获取两个首字母缩写词列表,每个单词 1 个列表。第一个 for 循环一切都很好。在我尝试了第二个词后,我得到:

syn2 = wn.synsets(word)[0].lemmas[y]
IndexError: list index out of range

希望有人可以帮助我理解为什么会发生这种情况。

import nltk
from nltk.corpus import wordnet as wn
import string
from array import * 

syn1 = '' 
syn2 = '' 
mylist = []    
mylist2 = []    
mylist3 = []  


Web_Keywd = 'car loan'
wuser_words = Web_Keywd.split()   

for word in wuser_words:                           


     i=i+1
     #first
     if (i == 1) :
         synset1 = wn.synsets(word)    
         y = 0     
         for synset in synset1:
             syn1 = wn.synsets(word)[0].lemmas[y]
             syn1 = syn1.name
             mylist2.append(syn1)
             y=y+1
     if (i == 2) :
         y = 0     
         for synset2 in wn.synsets(word):
             syn2 = wn.synsets(word)[0].lemmas[y]
             syn2 = syn2.name
             mylist3.append(syn2)
             y=y+1  
4

1 回答 1

1

我之前的回答中使用wn.synsets(word)[0].lemmas[y]. 您需要显式地遍历引理,因为您无法提前知道有多少引理。示例用例:

Web_Keywd = 'car loan cheap'

results = {}
for word in Web_Keywd.split():
    for synset in wn.synsets(word):
        for lemma in synset.lemmas:
            results.setdefault(word, []).append(lemma.name)

results现在看起来如下:

{'car': ['car', 'auto', 'automobile', 'machine'...],
'loan': ['loan', 'loanword', 'loan', 'lend', 'loan'...],
'cheap': ['cheap', 'inexpensive', 'brassy', 'cheap...]}

要获得提交的每个单词的唯一结果,独立于其他单词

.... # same as above
            results.setdefault(word, set()).add(lemma.name)

要获取所有提交的单词的唯一单词列表:

Web_Keywd = 'car loan cheap'

words = set(Web_Keywd.split())
results = set(
    lemma.name
    for word in words
        for synset in wn.synsets(word)
            for lemma in synset.lemmas
)
# results -> {'loanword', 'tatty', 'automobile', 'cheap', 'chinchy',...
于 2013-06-21T15:30:48.653 回答