gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:29:04 25 4
gpt4 key购买 nike

我正在使用 Python (2.7) 以及自然语言工具包 (3.2.1) 和 WordNet。我非常编程新手。

我正在尝试编写一个程序,它要求用户输入一个词,然后打印该词的同义词集,然后询问用户它希望查看哪个同义词集的词条。

问题是 raw_input 只接受字符串,所以当我尝试在用户输入上使用方法 .lemma_names() 时,出现错误 AttributeError: 'str' 对象没有属性 '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

关于python - 如何将用户输入的字符串转换为正确的对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38986720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com