Chapter 1: Language

Section 1: Generating Sentences

We have generated language in several ways in this class already.

One way was with the simple language generator. We typed in a model (a sentence pattern) and a dictionary of words by parts.

_images/SentenceGenerator.png

We have also done sentence generation in Snap. We have a language generation project that lets us generate sentences by parts, just like in the simple language generator.

_images/picking-words-from-variables.png

The Python Version V1

The below program does the same thing in Python. Click ‘Run’ to generate a random sentence.

Try answering these questions about the code above.

The Python Version V2

The below program does the same thing in Python. Click ‘Run’ to generate a random sentence.

Try answering these questions about the code above.

Section 2: Creating a little Python chatbot

You have built Chatbots in Snap!. Here’s an example of a little one:

_images/Snap-kinda-chatbot.png

Here is a (very) little Python chatbot. This one is a little more sophisticated than our Snap chatbot – it can pick out a name from an input sentence, and it can do the equivalent of respond randomly that we saw in Charla-bot.

Python here in a Runestone ebook can’t receive user input, so let’s just change the inputSentence variable to represent what the user says. Press Run to see what the chat bot responds.

This code is recognizing words in the inputSentence then deciding what to print in response.

  • inputSentence.split() breaks up the input into distinct words.

  • The first block that starts with if is asking if the input sentence contains the word “name”.

    • If the word “name” is there, the function index tells us where “name” appears. That goes in nameIndex.

    • If the word “is” is just after “name”, then we guess that the next word is the user’s name. Put that in yourName.

    • Then, print out a greeting for the specific name. (Remember that bots often focus on one word the user says.)

  • If the word “name” isn’t there, we check all the possible greetings words.

    • If one of those greeting words is in the input sentence, then print a basic “Hi, how are you?”

    • If we do find a greeting word, we set a variable that we found one. We break out of the loop checking the greeting words.

    • If we did not find a greeting word (not found), then we print a random question back to the user.

You have attempted of activities on this page