[Tutor] Searching through text with multiple answers
Mats Wichmann
mats at wichmann.us
Sun Nov 17 13:09:42 EST 2019
On 11/17/19 9:42 AM, samhar zghaier wrote:
> Hello
> I'm trying to make a search function through a small text file
> i created a function to split my text and put into a list
>
> my goal right now is to create a search function that shows tha the
> results of my search and confirms its existence in the text file. however i
> do not know how to do it if a few of my elements share a name
>
> can you help me please
>
> This is how i am splitting my text:
>
> def split_text():
> file_name = "text.txt"
> list_of_everything = []
>
> with open(file_name) as file:
> for line in file:
> list_of_everything.append(line.strip())
while we're waiting for your replies to the questions already raised,
you could rewrite this little snippet as follows:
def split_text_from_file(file_name):
with open(file_name, "r") as f:
return [line.strip() for line in f]
list_of_everything = split_text_from_file("text.txt")
i.e. don't wire in the filename to read, and process more concisely.
there's not much reason to write a function if you're not going to pass
it some data to work on; the way you have it written your function has
"side effects", even "magic" (that it knows the filename) and that's
usually considered less than optimal.
If you haven't gotten to list comprehensions yet, that's okay, but
they're certainly worth learning eventually.
More information about the Tutor
mailing list