practice.py
import re
practice.py
question = "When? where? who? What did you do?"
practice.py
def four_ws_game(sentence):
words = re.findall(".*??", sentence)
i = 0
while i < len(words):
answer = input(f"{words[i]}:").strip()
if answer == "":
print("Please do it seriously")
else:
sentence = sentence.replace(words[i], answer)
i += 1
print(sentence)
It's hard to understand, so let's disassemble it.
--The findall function lists the ** matched parts ** in the sentence and passes it to the variable words. --. (Period) ** in regular expressions means any single character - \ * (asterisk) ** means repeat
practice.py
words = re.findall(".*??", sentence)
In other words, this program is at the end of the sentence (sentense) **? Words with any number of characters with (double-byte question) ** Find and list.
-**? (Half-width question) ** is necessary to extract the above words one by one. -Let's see how the contents of the list change depending on the presence or absence of? (Half-width question)
practice.py
words = re.findall(".*??", sentence)
print(words)
Execution result
['When?', 'where?', 'who?', 'What did you do?']
practice.py
words = re.findall(".*?", sentence)
print(words)
Execution result
['When? where? who? What did you do?']
practice.py
i = 0
while i < len(words):
answer = input(f"{words[i]}:").strip()
if answer == "":
print("Please do it seriously")
else:
sentence = sentence.replace(words[i], answer)
i += 1
print(sentence)
practice.py
four_ws_game(question)
practice.py
import re
question = "When? where? who? What did you do?"
def four_ws_game(sentence):
words = re.findall(".*??", sentence)
i = 0
while i < len(words):
answer = input(f"{words[i]}:").strip()
if answer == "":
print("Please do it seriously")
else:
sentence = sentence.replace(words[i], answer)
i += 1
print("What happened? :" + sentence)
four_ws_game(question)
When?:Yesterday
where?:At home
who?:Cat
What did you do?:I fell asleep
What happened? : The cat fell at home yesterday
--I get angry when I try to leave it blank
When?:Yesterday
where?:
Please do it seriously
where?:At home
who?:Cat
What did you do?:
Please do it seriously
What did you do?:Became a dog
What happened? : The cat became a dog at home yesterday
Recommended Posts