2016-08-17 76 views
3

我正在使用Python(2.7)以及自然語言工具包(3.2.1)和WordNet。我是很新編程新手。如何將用戶輸入字符串轉換爲正確的對象類型

我正在嘗試編寫一個程序,要求用戶輸入一個單詞,然後打印該單詞的同義詞集,然後詢問用戶要查看哪個同義詞集。

問題是raw_input只接受字符串,所以當我嘗試在用戶輸入上使用方法.lemma_names()時,出現錯誤AttributeError: 'str' object has no attribute 'lemma_names'

下面是代碼:

from nltk.corpus import wordnet as wn 

w1 = raw_input ("What is the word? ") 

#This prints the synsets for w1, thus showing them what format to use in the next question. 

for synset in wn.synsets(w1): 
    print synset 

#This asks the user to choose the synset of w1 that interests them. 

synset1 = raw_input ("Which sense are you looking for? [Use same format as above]") 

#This prints the lemmas from the synset of interest. 

for x in synset1.lemma_names(): 
    print x 

我的問題是,如何從一個字符串,我可以使用.lemma_names()方法上的同義詞集合型轉換用戶的輸入?

我很抱歉,如果這個問題是如此基本以至於離題。如果是這樣,讓我知道。

+0

之前你寫任何代碼,下載[PyCharm(https://www.jetbrains.com/pycharm/download/)。使用它的調試器。 –

回答

1

試試這個:

from nltk.corpus import wordnet as wn 

w1 = raw_input ("What is the word? ") 

synset_dict = dict() 
for synset in wn.synsets(w1): 
    name = synset.name() 
    synset_dict[name] = synset 
    print name 

synset1 = raw_input ("Which sense are you looking for? [Use same format as above] ") 

if synset1 in synset_dict: 
    synset = synset_dict[synset1] 
    for lemma in synset.lemma_names(): 
     print lemma 
相關問題