The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.
The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.
How can I remove "The" from the movie title?
def userInput(lastInput):
if lastInput == None:
return str(input("Enter a movie title: ")).lower()
if lastInput[:4] == "The ": # doesn't work
lastInput = lastInput[4:] # doesn't work
while True:
userChoice = str(input("Enter a movie title: ")).lower()
if userChoice[0] == lastInput[-1]:
return userChoice
else:
print("\nInvalid input, what would you like to do?")
instructions()
You can replace the Part of the string In The case You Mentioned THE with an empty string ,
use
The following Code to Remove the word You want from the string
str="The Incredibles"
str.replace("The","")
Consider using regular expressions
import re
a = r'^(\bthe\b)'
sts = ['the incredibles', 'theodore', 'at the mueseum', 'their words' ]
for i in sts:
b = re.sub(a,'', i)
print(b)
The regular expression I am using seems to work, but you might want to test more examples, using this link https://regex101.com/r/pX5sD5/3
You could do this:
if lastInput.lower().startswith("the "): lastInput = lastInput[4:]
Using the startswith() method of strings, you can test for the first word directly (including the space that follows it). In order to support various capitalisation, turning the string to lowercase (using lower()) allows you to only perform one test for any combinations of upper/lower case variants (e.g. "The ", "the ", "THE ").
I also noticed that you are not applying this exclusion logic to the userChoice variable which is where I would have expected this to be used rather than on the lastInput variable.
Related
Need to write a code for a school lab.
Input is First name Middle name Last Name
Output needs to be Last name, First initial. Middle Initial.
It must also work with just first and last name.
Examples:
Input: Jane Ann Doe
Output: Doe, J. A.
Input: Jane Doe
Output: Doe, J.
Code thus far is:
# 2.12 Lab, input First name Middle name last name
# result to print Last name, fist initial. Middle initial period.
# result must account for user not having middle name
name = input()
tokens = name.split()
I do not understand how to write an if statement followed by print statement to get the desired output.
name = input("Enter name: ")
tokens = name.split()
if int(len(tokens)) > 2:
print(tokens[-1] + ",", tokens[0][0]+".", tokens[1][0]+".")
else:
print(tokens[-1] + ",", tokens[0][0]+".")
With what you have so far, tokens will be a list of the words you entered, such as ['Jane', 'Ann', 'Doe'].
What you need to do is to print out the last of those items in full, followed by a comma. Then each of the other items in order but with just the first letter followed by a period.
You can get the last item of a list x with x[-1]. You can get each of the others with a loop like:
for item in x[:-1]:
doSomethingWith(item)
And the first character of the string item can be extracted with item[0].
That should hopefully be enough to get you on your way.
If it's not enough, read on, though it would be far better for you if tou tried to nut it out yourself first.
...
No? Okay then, here we go ...
The following code shows one way you can do this, with hopefully enough comments that you will understand:
import sys
# Get line and turn into list of words.
inputLine = input("Please enter your full name: ")
tokens = inputLine.split()
print(tokens)
# Pre-check to make sure at least two words were entered.
if len(tokens) < 2:
print("ERROR: Need at least two tokens in the name.")
sys.exit(0)
# Print last word followed by comma, no newline (using f-strings).
print(f"{tokens[-1]},", end="")
# Process all but the last word.
for namePart in tokens[:-1]:
# Print first character of word followed by period, no newline.
print(f" {namePart[0]}.", end="")
# Make sure line is terminated by a newline character.
print()
You could no doubt make that more robust against weird edge cases like a first name of "." but it should be okay for an educational assignment.
But it handles even more complex names such as "River Rocket Blue Dallas Oliver" (yes, I'm serious, that's a real name).
# 2.12 Lab, input First name Middle name last name
# result to print Last name, fist initial. Middle initial period.
# result must account for user not having middle name
name = input()
tokens = name.split()
if len(tokens) == 2: # to identify if only two names entered
last_name = tokens[1]
first_init = tokens[0][0]
print(last_name, ',', first_init,'.',sep='')
if len(tokens) == 3: # to identify if three names entered
last_name = tokens[2]
first_init = tokens[0][0]
middle_init = tokens [1][0]
print(last_name, ',',' ',first_init,'.', ' ', middle_init,'.',sep='')
Try this code:
a=input()
name=a.split(" ")
index=len(name)
if index==3:
print(f"{name[-1]},{name[-3][0]}.{name[-2][0]}.")
else:
print(f"{name[-1]},{name[-2][0]}.")
Here is the explanation of the code:
First,using input(),we get the name of the person.
Then,we split the name using .split()with the parameter (written in the parenthesis) as " "
next we will find the no.of elements in the list (.split() returns a list) for the if statement
Then we print the output through the if statement shown above and using indexing ,we extract the first letter.
I was going through and example and it has this thing written " Check if their is more than one item in python string"
So how to check for multiple entries in string using in keyword?
Example:
items = input("Enter the name of items: ")
if "table" in items:
print("Its a table")
if "chair" in items:
print("Its a chair")
This program will work smooth for the sentence having table and chair in it. Now what i want is to get the output like "two or more items are entered" if I Input "table chair sofa"
Here you go.
items = 'table chair sofa'
words = items.split()
for word in words:
print(word)
if (len(words)) > 1:
print('two or more items entered')
So I am making this troubleshooting system related to phones in Python that needs to give a solution after looking at the user's query. In my list, the keywords that will be matched to the user's query are first put in and then the relevant solution to those keywords. The problem is that different issues that the user might have have different number of keywords to choose from and if all of the solutions in my list start with a symbol such as { how can I write a code that prints the next item in the list starting with { ?
storage = ["wet", "water", "toilet", "{Wipe the phone and place it in a bag of rice for 24 hours.}"]
This is an example of the list that I made. The user's query is: "I dropped my phone in the toilet."
The solution to this problem is right after the word 'toilet' starting with a curly bracket. Can you please provide me with a code that will make the program print the next value in the list that starts with a curly bracket?
Given a starting point like:
query = "I dropped my phone in the toilet."
storage = ["wet", "water", "toilet", "{Wipe the phone and place it in a bag of rice for 24 hours.}"]
First we would need some kind of flag that indicates when we have found a matching keyword, lets say:
found_word = False
then we just iterate over storage like so:
for word in storage:
however not all the entries in storage are keywords, some are special values that need to be treated differently:
for word in storage:
if word.startswith("{"):
When we encounter a value like this, if we have found a keyword we want to print out this special value then stop looping:
if word.startswith("{"):
if found_word:
print(word)
break
otherwise if the keyword is in the query then we just set the flag to True:
elif word in query:
found_word = True
so our final code would be:
found_word = False
for word in storage:
if word.startswith("{"):
if found_word:
print(word)
break
elif word in query:
found_word = True
on the other hand, if you used a dict to store your data like:
wet_solve = "Wipe the phone and place it in a bag of rice for 24 hours."
solutions = {"wet":wet_solve, "water":wet_solve, "toilet":wet_solve}
Then you would just need to check all the words in the query for one in the solutions:
for word in query.split():
if word in solutions:
print(solutions[word])
The following will do exactly what you asked: "Can you please provide me with a code that will make the program print the next value in the list that starts with a curly bracket?"
def findNextCurly(keyword):
index = storage.index(keyword) + 1
while not storage[index].startswith("{"):
index = index+1
print (storage[index][1:-1])
>>> findNextCurly('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in findNextCurly
ValueError: 'test' is not in list
>>> findNextCurly('wet')
Wipe the phone and place it in a bag of rice for 24 hours.
... but nothing more.
The notation string[1:-1] is called string slicing and is explained in the official tutorial. Here it is used to remove the first and last characters from the string – the curly brackets.
The solution given by Rad Lexus will return any value that has a curly brace in it, i.e. it would also print hello{brace. If you only want the ones that start with a letter, try:
storage = ["wet", "water", "toilet", "{Wipe the phone and place it in a bag of rice for 24 hours.}"]
for s in storage:
if s.startswith("{"):
print(s)
As a newbie to programming I currently have an exam where I am supposed to submit Python code for a madlibs game. What I am currently missing in my code is the validation of the user input against the word that should appear in the text.
Right now the program is able to take user input and display the full text but I don't know where to put the validation of the user input in my code, especially because I am going through a list of different words. I know that I have to define the variable somewhere to make a check against the user input but I am completely stuck right now.
This is the current working version of my code, i.e. without the attempt of the input validation against the words.
print "Welcome to my first quiz with user input"
print "Lets get cracking straight away"
print
import time
while True:
difficulty_level = raw_input("Which difficulty level would you like? Type EASY, MEDIUM or HARD to continue? ")
if difficulty_level.upper() == "EASY":
time.sleep(1)
print "Here it goes..."
print
time.sleep(1)
print "Here's your text. Should be an easy one. Just fill in the blanks for _Word_ 1-3."
print
print
print "Python is a _Word1_ language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December _Word2_ by Guido von Rossum. The most simple _Word3_ in Python is _Word4_ and normally used at the beginning to tell Python to write 'Hello World' on the screen."
print
# A list of replacement words to be passed in to the play game function.
parts_of_speech1 = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
# The following is the text for the easy text..
easy_text = "Python is a _Word1_ language that provides constructs intended to enable clear programs on both small and large scale. Python implementation was started in December _Word2_ by Guido von Rossum. The most simple _Word3_ in Python is _Word4_ and normally used at the beginning to tell Python to write 'Hello World' on the screen."
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_easy(word, parts_of_speech1):
for pos in parts_of_speech1:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in the easy text,
# which appear in parts_of_speech with their own words.
def easy_game(easy_text, parts_of_speech1):
replaced = []
easy_text = easy_text.split()
for word in easy_text:
replacement = word_in_pos_easy(word, parts_of_speech1)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
time.sleep(1)
print "Ok, lets see your results. Does it make sense?"
print
time.sleep(1)
return replaced
print
time.sleep(1)
print easy_game(easy_text, parts_of_speech1)
# Difficulty Level Medium
if difficulty_level.upper() == "MEDIUM":
time.sleep(1)
print "Good choice. Lets see how much you know about Python"
print
time.sleep(1)
print "Here's your text. It's a tricky one that requires some more knowledge about Python. Just fill in the blanks for _Word_ 1-3."
print
print
print "A string object is _Word1_, i.e. it cannot be modified after it has been created. An important concept in Python and other programming languages is _Word2_. You use them to store a value. To assign a value to a Variable you use the _Word3_ operator. A more versatile data type in Python is _Word4_. They contain items separated by commas and within square brackets. To some extent they are similar to arrays in C."
print
# A list of replacement words to be passed in to the play game function.
parts_of_speech2 = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
# The following are some test strings to pass in to the play_game function.
medium_text = "A string object is _Word1_, i.e. it cannot be modified after it has been created. An important concept in Python and other programming languages is _Word2_. You use them to store a value. To assign a value to a Variable you use the _Word3_ operator. A more versatile data type in Python is _Word4_. They contain items separated by commas and within square brackets. To some extent they are similar to arrays in C."
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_medium(word, parts_of_speech2):
for pos in parts_of_speech2:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in ml_string,
# which appear in parts_of_speech with their own words.
def medium_game(medium_text, parts_of_speech2):
replaced = []
medium_text = medium_text.split()
for word in medium_text:
replacement = word_in_pos_medium(word, parts_of_speech2)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
time.sleep(1)
print "OK, lets see your results. Does it make sense?"
print
time.sleep(1)
return replaced
print
time.sleep(1)
print medium_game(medium_text, parts_of_speech2)
# Difficulty Level Hard
if difficulty_level.upper() == "HARD":
time.sleep(1)
print "Bold move! Here we go. Check out this text. It's a tough one"
print
time.sleep(1)
print "Here's your text. This one requires quite some Python knowledge"
print
print
print "Similar to other programming languages, Python has flow controls. The most known statement is the _Word1_ statement. It can be combined with an else statement and helps to process a logic based on a specific condition. For more repetitive processing one needs to use loops. _Word2_ loops execute a sequence of statements multiple times and abbreviates the code that manages the loop variable._Word3_ loops repeat a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body."
print
# A list of replacement words to be passed in to the play game function.
parts_of_speech3 = ["_Word1_", "_Word2_", "_Word3_", "_Word4_"]
# The following are some test strings to pass in to the play_game function.
hard_text = "Similar to other programming languages, Python has flow controls. The most known statement is the _Word1_ statement. It can be combined with an else statement and helps to process a logic based on a specific condition. For more repetitive processing one needs to use loops. _Word2_ loops execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. _Word3_ loops repeat a statement or group of statements while a given condition is TRUE. It tests the _Word4_ before executing the loop body."
# Checks if a word in parts_of_speech is a substring of the word passed in.
def word_in_pos_hard(word, parts_of_speech3):
for pos in parts_of_speech3:
if pos in word:
return pos
return None
# Plays a full game of mad_libs. A player is prompted to replace words in the hard text,
# which appear in parts_of_speech with their own words.
def hard_game(hard_text, parts_of_speech3):
replaced = []
hard_text = hard_text.split()
for word in hard_text:
replacement = word_in_pos_hard(word, parts_of_speech3)
if replacement != None:
user_input = raw_input("Type in: " + replacement + " ")
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
print
time.sleep(1)
print "OK, lets see your results. Does it make sense?"
print
time.sleep(1)
return replaced
print
print hard_game(hard_text, parts_of_speech3)
else:
print "Sorry, that was not a correct input. Please enter EASY, MEDIUM or HARD to set the difficulty level."
Here's how I would do it:
from random import shuffle
import sys
from time import sleep
# version compatibility shim
if sys.hexversion <= 0x3000000: # Python 2.x
inp = raw_input
else: # Python 3.x
inp = input
def get_word(prompt):
return inp(prompt).strip().lower()
def shuffled(words):
words_copy = list(words)
shuffle(words_copy)
return words_copy
class MadLib:
BLANK = "___"
DELAY = 1
def __init__(self, intros, prompt, words):
self.intros = intros
self.prompt = prompt
self.words = words
self.num_words = len(words)
assert prompt.count(self.BLANK) == self.num_words, "Number of blanks must match number of words!"
def play(self):
# show introduction
for s in self.intros:
sleep(self.DELAY)
print(s, flush=True)
# display madlib with blanks
sleep(self.DELAY)
print(self.prompt)
# get words from user
print("Words available: " + ", ".join(shuffled(self.words)))
gotten = [
get_word("Word {}: ".format(i))
for i in range(1, self.num_words + 1)
]
# evaluate results
num_right = sum(g == w for g,w in zip(gotten, self.words))
if num_right == self.num_words:
print("You did it!")
return True
else:
print("You got {} out of {} words right.".format(num_right, self.num_words))
return False
madlibs = {
"easy":
MadLib(
[
"Here we go...",
"Here's your text. Should be an easy one.",
"Just fill in the blanks!"
],
(
"Python is a ___ language that provides constructs intended to "
"enable clear programs on both small and large scale. "
"Python implementation was started in December ___ by "
"Guido von Rossum. The most basic ___ in Python is ___, "
"often used by beginners to tell Python to display 'Hello "
"World' on the screen."
),
['programming', '1989', 'command', 'print']
),
"medium":
MadLib(
[
"Good choice. Lets see how much you know about Python",
"Here's your text. It's a tricky one that requires some more knowledge about Python.",
"Just fill in the blanks!"
],
(
"A string object is ___, i.e. it cannot be modified after it "
"has been created. An important concept in Python and other "
"programming languages is the ___, used to store a value. "
"To assign a value to you use the ___ operator. A more "
"versatile data type in Python is ___, containing items "
"separated by commas and within square brackets and to "
"some extent they are similar to arrays in C."
),
['immutable', 'variable', 'equals', 'list']
),
"hard":
MadLib(
[
"Bold move! Here we go. Check out this text. It's a tough one!",
"Here's your text. This one requires quite some Python knowledge.",
"Just fill in the blanks!",
"Here's your text:"
],
(
"Similar to other programming languages, Python has flow "
"control commands. The most common is ___ which lets you branch "
"based on a condition. Looping commands like ___ execute "
"statements a given number of times, or ___ repeats statements "
"so long as a condition is True."
),
['if', 'for', 'while']
)
}
def main():
print(
"Welcome to my first quiz with user input!\n"
"Lets get cracking straight away."
)
while True:
choice = get_word("Which difficulty level would you like? [easy, medium, hard] (or just hit Enter to exit) ")
if not choice:
break
elif choice in madlibs:
madlibs[choice].play()
else:
print("Sorry, that was not a recognized option.")
if __name__=="__main__":
main()
I am making a simple chat bot in Python. It has a text file with regular expressions which help to generate the output. The user input and the bot output are separated by a | character.
my name is (?P<'name'>\w*) | Hi {'name'}!
This works fine for single sets of input and output responses, however I would like the bot to be able to store the regex values the user inputs and then use them again (i.e. give the bot a 'memory'). For example, I would like to have the bot store the value input for 'name', so that I can have this in the rules:
my name is (?P<'word'>\w*) | You said your name is {'name'} already!
my name is (?P<'name'>\w*) | Hi {'name'}!
Having no value for 'name' yet, the bot will first output 'Hi steve', and once the bot does have this value, the 'word' rule will apply. I'm not sure if this is easily feasible given the way I have structured my program. I have made it so that the text file is made into a dictionary with the key and value separated by the | character, when the user inputs some text, the program compares whether the user input matches the input stored in the dictionary, and prints out the corresponding bot response (there is also an 'else' case if no match is found).
I must need something to happen at the comparing part of the process so that the user's regular expression text is saved and then substituted back into the dictionary somehow. All of my regular expressions have different names associated with them (there are no two instances of 'word', for example...there is 'word', 'word2', etc), I did this as I thought it would make this part of the process easier. I may have structured the thing completely wrong to do this task though.
Edit: code
import re
io = {}
with open("rules.txt") as brain:
for line in brain:
key, value = line.split('|')
io[key] = value
string = str(raw_input('> ')).lower()+' word'
x = 1
while x == 1:
for regex, output in io.items():
match = re.match(regex, string)
if match:
print(output.format(**match.groupdict()))
string = str(raw_input('> ')).lower()+' word'
else:
print ' Sorry?'
string = str(raw_input('> ')).lower()+' word'
I had some difficulty to understand the principle of your algorithm because I'm not used to employ the named groups.
The following code is the way I would solve your problem, I hope it will give you some ideas.
I think that having only one dictionary isn't a good principle, it increases the complexity of reasoning and of the algorithm. So I based the code on two dictionaries: direg and memory
Theses two dictionaries have keys that are indexes of groups, not all the indexes, only some particular ones, the indexes of the groups being the last in each individual patterns.
Because, for the fun, I decided that the regexes must be able to have several groups.
What I call individual patterns in my code are the following strings:
"[mM]y name [Ii][sS] (\w*)"
"[Ii]n repertory (\w*) I [wW][aA][nN][tT] file (\w*)"
"[Ii] [wW][aA][nN][tT] to ([ \w]*)"
You see that the second individual pattern has 2 capturing groups: consequently there are 3 individual patterns, but a total of 4 groups in all the individual groups.
So the creation of the dictionaries needs some additional care to take account of the fact that the index of the last matching group ( which I use with help of the attribute of name lastindex of a regex MatchObject ) may not correspond to the numbering of individual regexes present in the regex pattern: it's harder to explain than to understand. That's the reason why I count in the function distr() the occurences of strings {0} {1} {2} {3} {4} etc whose number MUST be the same as the number of groups defined in the corresponding individual pattern.
I found the suggestion of Laurence D'Oliveiro to use '||' instead of '|' as separator interesting.
My code simulates a session in which several inputs are done:
import re
regi = ("[mM]y name [Ii][sS] (\w*)"
"||Hi {0}!"
"||You said that your name was {0} !!!",
"[Ii]n repertory (\w*) I [wW][aA][nN][tT] file (\w*)"
"||OK here's your file {0}\\{1} :"
"||I already gave you the file {0}\\{1} !",
"[Ii] [wW][aA][nN][tT] to ([ \w]*)"
"||OK, I will do {0}"
"||You already did {0}. Do yo really want again ?")
direg = {}
memory = {}
def distr(regi,cnt = 0,di = direg,mem = memory,
regnb = re.compile('{\d+}')):
for i,el in enumerate(regi,start=1):
sp = el.split('||')
cnt += len(regnb.findall(sp[1]))
di[cnt] = sp[1]
mem[cnt] = sp[2]
yield sp[0]
regx = re.compile('|'.join(distr(regi)))
print 'direg :\n',direg
print
print 'memory :\n',memory
for inp in ('I say that my name is Armano the 1st',
'In repertory ONE I want file SPACE',
'I want to record music',
'In repertory ONE I want file SPACE',
'I say that my name is Armstrong',
'But my name IS Armstrong now !!!',
'In repertory TWO I want file EARTH',
'Now my name is Helena'):
print '\ninput ==',inp
mat = regx.search(inp)
if direg[mat.lastindex]:
print 'output ==',direg[mat.lastindex]\
.format(*(d for d in mat.groups() if d))
direg[mat.lastindex] = None
memory[mat.lastindex] = memory[mat.lastindex]\
.format(*(d for d in mat.groups() if d))
else:
print 'output ==',memory[mat.lastindex]\
.format(*(d for d in mat.groups() if d))
if not memory[mat.lastindex].startswith('Sorry'):
memory[mat.lastindex] = 'Sorry, ' \
+ memory[mat.lastindex][0].lower()\
+ memory[mat.lastindex][1:]
result
direg :
{1: 'Hi {0}!', 3: "OK here's your file {0}\\{1} :", 4: 'OK, I will do {0}'}
memory :
{1: 'You said that your name was {0} !!!', 3: 'I already gave you the file {0}\\{1} !', 4: 'You already did {0}. Do yo really want again ?'}
input == I say that my name is Armano the 1st
output == Hi Armano!
input == In repertory ONE I want file SPACE
output == OK here's your file ONE\SPACE :
input == I want to record music
output == OK, I will do record music
input == In repertory ONE I want file SPACE
output == I already gave you the file ONE\SPACE !
input == I say that my name is Armstrong
output == You said that your name was Armano !!!
input == But my name IS Armstrong now !!!
output == Sorry, you said that your name was Armano !!!
input == In repertory TWO I want file EARTH
output == Sorry, i already gave you the file ONE\SPACE !
input == Now my name is Helena
output == Sorry, you said that your name was Armano !!!
OK, let me see if I understand this:
You want to a dictionary of key-value pairs. This will be the “memory” of the chatbot.
You want to apply regular-expression rules to user input. But which rules might apply is conditional on which keys are already present in the memory dictionary: if “name” is not yet defined, then the rule that defines “name” applies; but if it is, then the rule that mentions “word” applies.
Seems to me you need more information attached to your rules. For example, the “word” rule you gave above shouldn’t actually add “word” to the dictionary, otherwise it would only apply once (imagine if the user keeps trying to say “my name is x” more than twice).
Does that give you a bit more idea about how to proceed?
Oh, by the way, I think “|” is a poor choice for a separator character, because it can occur in regular expressions. Not sure what to suggest: how about “||”?