以最面向对象的方式创建和读取多个选项的列表?

2024-05-14 07:48:26 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这个标题听起来有点混乱,但我将试图在我的解释透彻。我目前正在用Python编程一个bot,它被设计成基于关键字的双关语做出适当的响应。每个词都有多个潜在的反应,但同样地,每个反应都可以用于多个词。你知道吗

例如,如果在cat_input(见下文)中找到一个单词,它将产生来自cat_output的随机响应。你知道吗

cat_input= ['cat','purr','meow','claw','felidae','puss','paw']
cat_output= ["I know the purrfect pun for that one.",
             "I only tell these puns beclaws I have to."
            ]

然而,“爪”和“爪”这个词也可以用于其他动物,其他动物也可能具有相同的潜在输出,如下所示:

dog_input=['dog','woof','bark','paw','canine','pup','puppy','claw']

dog_output=["I only tell these puns beclaws I have to.",
            "I knew a dog who was a little ruff on me."
          ]

正如你所看到的,这并不是最佳的,这让我想到了标题问题:什么是最好的面向对象的方法,能够以较少的重复将某些单词分类到某些回答中(如果可能的话),你能给出一个基本的例子来解释它可能看起来如何?你知道吗


Tags: to标题onlyinputoutputhave单词cat
3条回答

如何创建一个基类Animal,从中DogCat继承?然后可以检查单词paw是否与动物匹配,然后随机选择一个Animal实例。你知道吗

也许是为了抽象,或者我没有真正得到你想要的。但为什么你有不同的意见?我觉得没关系。。。我会创建一个简单的dict,将每个单词与它的潜在输出相匹配,然后从中随机地grep一个。。。你知道吗

试试这个:

import random
class petPun(object):
    def __init__(self, species,inputWordList,outputSentenceList):
        self.species=species
        self.inputWordList=inputWordList
        self.outputSentenceList=outputSentenceList
    def makePun(self,inputWord):
        if inputWord in self.inputWordList:
            random.shuffle(self.outputSentenceList)
            return self.outputSentenceList[0]
        else:
            return "Invalid Word"

animalInputDict={"Dog":['Dog','Woof','Bark','Paw','Canine','Pup','Puppy','Claw'],"Cat":['Cat','Purr','Meow','Claw','Felidae','Puss','Paw']}
animalOutputDict={"Dog":["I only tell these puns beclaws I have to.","I knew a dog who was a little ruff on me."],"Cat":["I know the purrfect pun for that one.","I only tell these puns beclaws I have to."]}
while True:
    currentSpecies=input("What species of pun do you want?")

    punObject=petPun(currentSpecies,animalInputDict[currentSpecies],animalOutputDict[currentSpecies])
    word=input("What word do you want to base your pun off of?")
    pun=punObject.makePun(word)
    print(pun)
    exitUser=input("Do you want to stop making puns?")
    if exitUser=="Yes":
        break

我希望这有帮助。如果不能满足你的需要,就告诉我。另外,明智的做法是让它更安全。通过将它们添加到两个字典中,可以实现更多的动物。另一种方法是多态继承,如果这不起作用,您可以尝试这种方法。你知道吗

相关问题 更多 >

    热门问题