如何将用户输入的字符串转换为正确的对象类型

How to transform user input string into correct object type

我正在使用 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() 方法的同义词集类型?

如果这个问题太基础以至于跑题了,我深表歉意。如果是这样,请告诉我。

试试这个:

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