2016-08-17 56 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 
相关问题