Creating the Chatbot Program
Do you ever find yourself talking to your computer? Wouldn’t it be great if it could chat back? The next program enables you to have a conversation with your computer onscreen. Using a few tricks, we’ll make the program appear to be intelligent, and able to learn from what you type in. It’s not actual artificial intelligence, of course: That discipline of computer science is highly evolved, and this is a simple demo program. Chatbot can throw up some surprises, however, and you can expand its vocabulary to make it smarter. For a sneak preview of what it can do, see Figure 12-5 at the end of the chapter.
As you build this program, you’ll deepen your understanding of Python. In particular, you’ll learn about conditional statements, lists, dictionaries, and random choices.
The program works like this:
1. It introduces itself and then invites the player to respond.
2. The player types something in.
3. If the player types in
bye, the computer replies with a message to say thanks for chatting, and then finishes the program.
4. The program has stock responses for certain words, so it checks whether it recognizes any of the words that the player has entered. If it does, it uses one of the appropriate stock responses. If more than one stock response applies, the computer chooses one at random.
5. If none of the words are recognized, the program chooses a random phrase and replies with that. To stop the random phrases repeating, it replaces the phrase used ...