[英]How to read the user's input, searching for a pre-made list of strings, and then return the matched content in Python?
def prompter():定义提示器():
users_note = 'The distance between my accommodation and the campus is roughly two miles, with five tube stations in between.'
note_list = users_note.split()
i = 0
for users_voice in note_list:
if users_voice == note_list[i]:
users_voice = input('Enter words you gonna say next: ').split()
print(note_list[i])
i += 1
else:
print('Sorry, try again')
I am trying to create a small teleprompter prototype program that is able to return the content from the user's note every time a user says something, as long as it's within the pre-made list of strings.我正在尝试创建一个小型提词提示器原型程序,只要它在预先制作的字符串列表中,它就能够在每次用户说某事时从用户的笔记中返回内容。
So what the answer should return when calling this function should be:那么调用这个函数时应该返回的答案应该是:
>>> Enter words you gonna say next: my
>>> ‘my’
>>> Enter words you gonna say next: accommodation
>>> ‘accommodation’
>>> Enter words you gonna say next: roughly two miles
>>> ‘roughly two miles’
>>> Enter words you gonna say next: distance campus stations
>>> ‘distance campus stations’
>>> Enter words you gonna say next: foo
>>> ‘Sorry, try again’
When the user is trying to type a word that's not from that pre-made list of strings, the function will keep asking users until they've entered the correct input.当用户试图输入一个不是来自预先制作的字符串列表的单词时,该函数将不断询问用户,直到他们输入正确的输入。
However, I am not entirely sure how to come with such an algorithm/solution, I managed to implement it myself but the function didn't seem to return the output as expected, can someone here suggest a fix?但是,我不完全确定如何使用这样的算法/解决方案,我自己设法实现了它,但该函数似乎没有按预期返回输出,这里有人可以提出修复建议吗?
The question (or the intention of the question) is not 100% clear, but may you can use this, to run an endless loop to ask for new words.问题(或问题的意图)不是 100% 清楚,但您可以使用它,运行无限循环以询问新单词。 You can end the loop by
CTRL + C
:您可以通过
CTRL + C
结束循环:
def prompter():
users_note = 'The distance between my accommodation and the campus is roughly two miles, with five tube stations in between.'
note_list = users_note.split() # Be careful, that you have a dot after the last word !
while True: # Endless loop
words = input('Enter words you gonna say next: ').split()
for word in words: # For each word in input list
if word not in note_list:
print('Sorry, try again', end="")
break # ends the for loop
else:
print(word, end=" ")
print()
# Here you can add a condition to end the loop (maybe after 3 wrong inputs), to end the loop you can use 'break'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.