Skip to content

Instantly share code, notes, and snippets.

@tlancon
Created June 24, 2018 18:54
Show Gist options
  • Save tlancon/8010009b802a1323f95e1c6bc5e4454f to your computer and use it in GitHub Desktop.
Save tlancon/8010009b802a1323f95e1c6bc5e4454f to your computer and use it in GitHub Desktop.
Compares a user's input to a list of allowable reponses and returns the keyword.
def parse_response(multiple_choice, prompt=None):
"""
Splits a user's input into individual words and searches a list
of allowable responses for a unique match, then returns the word
that matches one of the options.
List comprehension syntax explained for my own reference:
1. for i in response.split() - breaks every word of response
into individual strings
2. if i in multiple_choice - searches for ALL recognized words
within list of possible keywords
3. [i for ...] - appends all intersections from the rest of the
list comprehension to a list
Arguments
---------
multiple_choice : list or dict
The options allowed within the user's response. If a dict
is passed, a list is generated from dict.keys().
prompt : string
If not specified, the prompt for user input prints a single
caret >. A string can be specified to print a more useful
prompt if need be.
Returns
-------
string
The keyword from the input that matches allowable options.
"""
if type(multiple_choice) is dict:
multiple_choice = multiple_choice.keys()
while True:
if prompt is None:
response = input('> ')
else:
response = input('< ' + prompt + ' >\n').lower()
keywords = [i for i in response.split() if i in multiple_choice]
if len(keywords) != 1:
print('Sorry, that is not an option or it wasn\'t recognized.\n'
'Try one of the following:')
print(multiple_choice)
continue
else:
return keywords[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment