patternpythonMinor
Return a random line from a file when user enters a specific text
Viewed 0 times
randomfilelinereturnusertextwhenentersfromspecific
Problem
I am a beginner trying to fetch a random line from a file and wondering if this code can be improved. Should I use try and catch in this case? Should I take a parameter for the function "quote"? How can I take several alternatives for
searchText? (E.g. "hello", "hi" or "hey" but one is enough to return true.) def getInputFromUser(inputText, verifier, error=None):
"""
General function to get input from the user, repeating the question until verifier returns true
"""
while True:
userInput = input(inputText)
if not verifier or verifier(userInput):
return userInput
elif error:
print(error)
def quote():
"""
Return a random line from a file if user enters the text "hello"
"""
searchText = "hello"
text = getInputFromUser("Enter a sentence with the words 'hello', 'hi' or 'hey': ", lambda inputText: inputText)
if searchText in text:
lineFetched = random.choice(open('myquotes.txt').readlines())
print("My quote: ", lineFetched)
else:
quote()Solution
When working with files, you should wrap
If you want to make it possible to match any of multiple words like "hello", "hi",
then you'd need a helper function, for example:
And then change your code to use this:
In the above examples I renamed the variable and method names to follow PEP8.
open calls in a with statement like this:if search_text in text:
with open('myquotes.txt') as fh:
line_fetched = random.choice(fh.readlines())
print("My quote: ", line_fetched)
else:
quote()If you want to make it possible to match any of multiple words like "hello", "hi",
then you'd need a helper function, for example:
def text_contains_any_of(text, words):
for term in words:
if term in text:
return True
return FalseAnd then change your code to use this:
words = ("hello", "hi")
if text_contains_any_of(text, words):
with open('myquotes.txt') as fh:
line_fetched = random.choice(fh.readlines())
print("My quote: ", line_fetched)In the above examples I renamed the variable and method names to follow PEP8.
Code Snippets
if search_text in text:
with open('myquotes.txt') as fh:
line_fetched = random.choice(fh.readlines())
print("My quote: ", line_fetched)
else:
quote()def text_contains_any_of(text, words):
for term in words:
if term in text:
return True
return Falsewords = ("hello", "hi")
if text_contains_any_of(text, words):
with open('myquotes.txt') as fh:
line_fetched = random.choice(fh.readlines())
print("My quote: ", line_fetched)Context
StackExchange Code Review Q#83303, answer score: 4
Revisions (0)
No revisions yet.