bot_template = "BOT : {0}"
user_template = "USER : {0}"
# Define a function that responds to a user's message: respond
def respond(message):
# Concatenate the user's message to the end of a standard bot respone
bot_message = "I can hear you! You said: " + message
# Return the result
return bot_message
# Test function
print(respond("hello!"))
# Create templates
bot_template = "BOT : {0}"
user_template = "USER : {0}"
# Define a function that sends a message to the bot: send_message
def send_message(message):
# Print user_template including the user_message
print(user_template.format(message))
# Get the bot's response to the message
response = respond(message)
# Print the bot template including the bot's response.
print(bot_template.format(response))
# Send a message to the bot
send_message("hello")
# Define variables
name = "Greg"
weather = "cloudy"
# Define a dictionary with the predefined responses
responses = {
"what's your name?": "my name is {0}".format(name),
"what's today's weather?": "the weather is {0}".format(weather),
"default": "default message"
}
# Return the matching response if there is one, default otherwise
def respond(message):
# Check if the message is in the responses
if message in responses:
# Return the matching message
bot_message = responses[message]
else:
# Return the "default" message
bot_message = responses["default"]
return bot_message
# Import the random module
import random
name = "Greg"
weather = "cloudy"
# Define a dictionary containing a list of responses for each message
responses = {
"what's your name?": [
"my name is {0}".format(name),
"they call me {0}".format(name),
"I go by {0}".format(name)
],
"what's today's weather?": [
"the weather is {0}".format(weather),
"it's {0} today".format(weather)
],
"default": ["default message"]
}
# Use random.choice() to choose a matching response
def respond(message):
if message in responses:
bot_message = random.choice(responses[message])
else:
bot_message = random.choice(responses["default"])
return bot_message
#def respond(message):
# Check for a question mark
if message.endswith("?"):
# Return a random question
return random.choice(responses["question"])
# Return a random statement
return random.choice(responses["statement"])
Define match_rule()
def match_rule(rules, message):
responses, phrase = "default", None
# Iterate over the rules dictionary
for pattern, responses in rules.items():
# Create a match object
match = re.search(pattern, message)
if match is not None:
# Choose a random response
response = random.choice(responses)
if '{0}' in response:
phrase = match.group(1)
# Return the response and phrase
return response.format(phrase)
# Test match_rule
print(match_rule(rules, "do you remember your last birthday"))
# Define replace_pronouns()
def replace_pronouns(message):
message = message.lower()
if 'me' in message:
# Replace 'me' with 'you'
return re.sub('me', 'you', message)
if 'my' in message:
# Replace 'my' with 'your'
return re.sub('my', 'your', message)
if 'your' in message:
# Replace 'your' with 'my'
return re.sub('your', 'my', message)
if 'you' in message:
# Replace 'you' with 'me'
return re.sub('you','me', message)
return message
print(replace_pronouns("my last birthday"))
print(replace_pronouns("when you went to Florida"))
print(replace_pronouns("I had my own castle"))
# Define respond()
def respond(message):
# Call match_rule
response, phrase = match_rule(rules, message)
if '{0}' in response:
# Replace the pronouns in the phrase
phrase = replace_pronouns(phrase)
# Include the phrase in the response
response = response.format(phrase)
return response
# Send the messages
send_message("do you remember your last birthday")
send_message("do you think humans should be worried about AI")
send_message("I want a robot friend")
send_message("what if you could be anything you wanted")
# Define a dictionary of patterns
patterns = {}
# Iterate over the keywords dictionary
for intent, keys in keywords.items():
# Create regular expressions and compile them into pattern objects
patterns[intent] = re.compile('|'.join (keys))
# Print the patterns
print(patterns)
# Define a function to find the intent of a message
def match_intent(message):
matched_intent = None
for intent, pattern in patterns.items():
# Check if the pattern occurs in the message
if pattern.search(message):
matched_intent = intent
return matched_intent
# Define a respond function
def respond(message):
# Call the match_intent function
intent = match_intent(message)
# Fall back to the default response
key = "default"
if intent in responses:
key = intent
return responses[key]
# Send messages
send_message("hello!")
send_message("bye byeee")
send_message("thanks very much!")
# Define find_name()
def find_name(message):
name = None
# Create a pattern for checking if the keywords occur
name_keyword = re.compile('name|call')
# Create a pattern for finding capitalized words
name_pattern = re.compile('[A-Z]{1}[a-z]*')
if name_keyword.search(message):
# Get the matching words in the string
name_words = name_pattern.findall(message)
if len(name_words) > 0:
# Return the name if the keywords are present
name = ' '.join(name_words)
return name
# Define respond()
def respond(message):
# Find the name
name = find_name(message)
if name is None:
return "Hi there!"
else:
return "Hello, {0}!".format(name)
# Send messages
send_message("my name is David Copperfield")
send_message("call me Ishmael")
send_message("People call me Cassandra")
# Load the spacy model: nlp
nlp = spacy.load('en')
# Calculate the length of sentences
n_sentences = len(sentences)
# Calculate the dimensionality of nlp
embedding_dim = nlp.vocab.vectors_length
# Initialize the array with zeros: X
X = np.zeros((n_sentences, embedding_dim))
# Iterate over the sentences
for idx, sentence in enumerate(sentences):
# Pass each each sentence to the nlp object to create a document
doc = nlp(sentence)
# Save the document's .vector attribute to the corresponding row in X
X[idx, :] = doc.vector
# Import SVC
from sklearn.svm import SVC
# Create a support vector classifier
clf = SVC(C=1)
# Fit the classifier using the training data
clf.fit(X_train, y_train)
# Predict the labels of the test set
y_pred = clf.predict(X_test)
# Count the number of correct predictions
n_correct = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
n_correct += 1
print("Predicted {0} correctly out of {1} test examples".format(n_correct, len(y_test)))
# Define included_entities
include_entities = ['DATE', 'ORG', 'PERSON']
# Define extract_entities()
def extract_entities(message):
# Create a dict to hold the entities
ents = dict.fromkeys(include_entities)
# Create a spacy document
doc = nlp(message)
for ent in doc.ents:
if ent.label_ in include_entities:
# Save interesting entities
ents[ent.label_] = ent.text
return ents
print(extract_entities('friends called Mary who have worked at Google since 2010'))
print(extract_entities('people who graduated from MIT in 1999'))
# Create the document
doc = nlp("let's see that jacket in red and some blue jeans")
# Iterate over parents in parse tree until an item entity is found
def find_parent_item(word):
# Iterate over the word's ancestors
for parent in word.ancestors:
# Check for an "item" entity
if entity_type(parent) == "item":
return parent.text
return None
# For all color entities, find their parent item
def assign_colors(doc):
# Iterate over the document
for word in doc:
# Check for "color" entities
if entity_type(word) == "color":
# Find the parent
item = find_parent_item(word)
print("item: {0} has color : {1}".format(item, word))
# Assign the colors
assign_colors(doc)