如何在Python

时间:2016-02-15 21:03:30

标签: python

所以,我正在制作一个聊天机器人,我想启用它,所以如果用户输入字典中的单词/短语(一个腌制文件),它将回复一个合适的消息,用户输入。如果你看到代码可能会更有意义:

""" startup """ 

import pickle

'''opening the dictionary'''

inFile = open('words.txt', 'rb')
dictionary = pickle.load(inFile)

'''printing the dictionary'''

print("PRE TESTS...")

print("-")

print("Pickle protocol import:")
print(dictionary)

print("END OF PRE TESTS...")

print("-")
print(" ")

""" end of startup """

print("Hello! My name is Pinnochio. I'm currently very young, and my communication is extremely limited.")
print("-")

''' handling the replies '''

reply = input()

if reply != dictionary:
    print("Sorry, I don't know that word.")
    reply = input()





if reply == dictionary[0] | dictionary[1] | dictionary[2]:
    print("Hey there")
    reply = input()

if reply == dictionary[3]:
    print("I'm feeling great!")
    reply = input()

if reply == dictionary[4] | dictionary[5]:
    print("It is, isn't it?")
    reply = input()

字典是另一个文件中的列表,我已经腌制了它:

import pickle

dictionary = ["hello", "hi", "hey", "how are you?", "good morning", "good afternoon"]

outFile = open('words.txt', 'wb')
pickle.dump(dictionary, outFile)
outFile.close()

提前致谢!

3 个答案:

答案 0 :(得分:1)

你应该让你的Server字典!

dictionary

然后你可以像这样使用它:

dictionary = {"hello": "Hey there",
              "hi": "Hey there",
              "hey": "Hey there",
              "how are you?": "I'm feeling great!",
              "good morning": "It is, isn't it?",
              "good afternoon": "It is, isn't it?",
              }

答案 1 :(得分:0)

使用in并切片来测试单词列表的一部分。

if reply in dictionary[0:3]:
    print("Hey there")

答案 2 :(得分:0)

这是你的问题:

if reply != dictionary:
    print("Sorry, I don't know that word.")
    reply = input()

dictionary是一个列表。因此,输入将永远不会等于列表。而且,就目前而言,用户实际上只进行了两次更改才能使其正确。你需要把它放在while循环中:

while(not reply in dictionary):
    print("Sorry, I don't know that word.")
    reply = input()

此外,正如评论中提到的那样,您应该更改变量名称。 dict是一种不同类型的数据结构。