Code a Story, Train a Bot¶
Learning Objectives
After today's activity, you should be able to:
- Explain the process of editing and running a Python program.
- Write simple Python programs that use
print()
andinput()
. - Train a chatbot by providing a variety of sample conversations.
- Describe how training data impacts the capability of a chatbot.
Python Basics¶
# How to input and output
name = input("Your name? ")
print("Hello", name + "!")
Story Generator¶
Starter Code: story.py
import random
# Define lists of phrases which will help build a story.
start = [
"Once upon a time,",
]
character = [
"there lived a child.",
]
time = [
"One day",
]
story_plot = [
"she was wandering near",
]
place = [
"the river, where",
]
second_character = [
"she saw a small bird,",
]
age = [
"shivering and wet,",
]
work = [
"searching for something.",
]
# Choose a random item from each list and print the story.
print(
random.choice(start),
random.choice(character),
random.choice(time),
random.choice(story_plot),
random.choice(place),
random.choice(second_character),
random.choice(age),
random.choice(work)
)
Code for Exercise #3
- Add this line at the top:
import textwrap
- Replace
print(
with:story = " ".join([
- Replace the
)
with:]) print(textwrap.fill(story, width=72))
Going Further¶
Simple Chatbot¶
Installation Commands
Run each command (in the Shell) after creating a venv.
!pip install chatterbot chatterbot_corpus pyyaml
!python -m spacy download en_core_web_sm
Starter Code: chat.py
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
# Name the bot
name = "ChatJMU"
bot = ChatBot(name)
# Train the bot
trainer = ListTrainer(bot)
trainer.train([
'How are you?',
'I am good.',
'What do you like?',
'Python programming',
'Thank you.',
'You are welcome.',
])
# Conversation loop
while True:
print() # blank line
request = input("You: ")
response = bot.get_response(request)
print(name + ":", response)
Code for Exercise #5
Add this after the other imports:
from chatterbot.trainers import ChatterBotCorpusTrainer
trainer = ChatterBotCorpusTrainer(bot)
trainer.train("chatterbot.corpus.english")