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

时间:2016-08-17 01:14:10

标签: python nltk wordnet

我正在使用Python(2.7)以及Natural Language Toolkit(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

我的问题是,如何将用户输入从字符串转换为synset类型,我可以使用.lemma_names()方法?

如果这个问题非常基本,那么我很抱歉。如果是这样,请告诉我。

1 个答案:

答案 0 :(得分: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