聊天机器人将在Python中获取输入和响应

时间:2016-09-10 09:52:32

标签: python list python-3.x

我目前正在尝试创建一个小版本的聊天机器人,它将响应终端中的不同关键字输入。例如,如果我写inv,它将打印出当前的库存,它可能如下所示:

Item: sword
Place in inventory: 1
Item: axe
Place in inventory: 2
Item: shield
Place in inventory: 3
Item: bow
Place in inventory: 4
Item: flower
Place in inventory: 5

那部分我已经解决了。当我要提供inv pick hammerinv drop hammer等输入时会出现此问题。现在我必须以某种方式处理在多种情况下可能出现相同的start关键字。

我创建了一种带有参数(来自用户的输入)并将其拆分为列表的处理程序。看起来像这样:

def splitIntoWords(argOne):
"""
Function that splits list into words
"""
#list to keep and split up the user input
inputList = []
inputList = argOne.split()
#print(str(inputList) + "splitIntoWords")
#term we want to search for
term = "citat"
quitOne = "q"
replyHej = "hej"
replyLunch = "lunch"
inventory = "inv"
invPick = "pick"

#invDrop = "drop"
lenght = len(inputList)
nextWord = inputList[lenght-1]



if term in inputList:
    return term
elif quitOne in inputList:
    return quitOne
elif replyHej in inputList:
    return replyHej
elif replyLunch in inputList:
    return replyLunch
elif inventory in inputList:
    if invPick in inputList:
        return ("q")
    else:
        return inventory
else:
    return result

正如你所看到的,我已经开始做了,如果在一个elif里面并试图在同一个列表上做多次检查,但它对我不起作用。 有没有其他方法可以检查,看到列表中出现多个关键字?

1 个答案:

答案 0 :(得分:0)

我格式化并测试了代码并且它可以工作。

def splitIntoWords( argOne):

    result = "hej"
    """
    Function that splits list into words
    """
    # list to keep and split up the user input
    inputList = []
    inputList = argOne.split()
    print(str(inputList) + "splitIntoWords")
    # term we want to search for
    term = "citat"
    quitOne = "q"
    replyHej = "hej"
    replyLunch = "lunch"
    inventory = "inv"
    invPick = "pick"

    # invDrop = "drop"
    lenght = len(inputList)
    nextWord = inputList[lenght - 1]

    if term in inputList:
        return term
    elif quitOne in inputList:
        return quitOne
    elif replyHej in inputList:
        return replyHej
    elif replyLunch in inputList:
        return replyLunch
    elif inventory in inputList:
        if invPick in inputList:
            return ("q")
        else:
            return inventory
    else:
        return result

print splitIntoWords("inv pick sword")

测试

python inventory.py 
['inv', 'pick', 'sword']splitIntoWords
q

以上q是预期结果。