Reputation: 33
I've been trying to add a function to my code which allows the user to search for certain keywords within a list of lists. It only works when the input is identical to the element but I want every element that contains the input to show.
infil = open("books.txt" , "r")
books_string = infil.read()
infil.close()
books_li = books_string.splitlines()
books_li.sort()
li_to_present= []
for element in books_li:
parts = element.split(",")
li_to_present.append(parts)
user_in = input("Search: ")
matches = [x for x in li_to_present if user_in in x]
Example:
Part of the list li_to_present
is:
['Birgitta Trotzig', ' Dykungens dotter'], ['Bo Giertz', ' Stengrunden']
If the users input is "Birgitta"
it won't append to the new list matches
Does anyone have a nice solution to this problem?
Upvotes: 2
Views: 71
Reputation: 49
import re
infil = open("books.txt" , "r")
books_string = infil.read()
infil.close()
books_li = books_string.splitlines()
books_li.sort()
li_to_present = []
for element in books_li:
parts = element.split(",")
li_to_present.append(parts)
user_in = input("Search: ")
matches = [x for x in li_to_present if re.search(user_in, x)]
Upvotes: 1
Reputation: 20414
Use the all()
function on a generator which yields whether the user input is in each string the sub-lists.
user_in = input("Search: ")
matches = [l for l in li_to_present if any(user_in in s for s in l)]
E.g.
>>> li_to_present = [['Birgitta Trotzig', ' Dykungens dotter'],
['Bo Giertz', ' Stengrunden']]
>>> user_in = input("Search: ")
Search: Birgitta
>>> matches = [l for l in li_to_present if any(user_in in s for s in l)]
>>> matches
[['Birgitta Trotzig', ' Dykungens dotter']]
Upvotes: 0