I have a database saved as a list of tuples, and every tuple has 4 elements. The first element is the book's number, the second element is the book's name, the third element is the book's author, and the forth element is the book's publishing year.
I need a function called findBook(L, keyword)
, that receives the books as a list of tuples, keyword
as a string, and returns all the tuples of books
that have keyword
in them. The tuple of the book
should be like this:
(BookNumber, BookName, Author, YearPublished)
How to write a search engine that will help us find these certain books?
I've tried to start with this, but it isn't working:
def findBook(L,keyword):
for i in L:
BookNumber=i[0]
BookName=i[1]
Author=i[2]
YearPublished=i[3]
i=(BookNumber,BookName,Author,YearPublished)
if keyword == str(BookName) or keyword==BookNumber or keyword==str(Author) or keyword==str(YearPublished):
return i
so if i have a harry potter book , and i enter the keyword : "harry" it should return all the whole tuple.
You could iterate over the entries that may have the keyword
you're looking for, grouping them into a list, that shall be returned by the end of the process:
def findBook(L, keyword):
books = list()
for book in L:
book = tuple(entry for entry in book)
if [i for i in book if str(i).find(keyword) != -1]:
books.append(book)
return books
L = [(2,"harry potter and the prisoner of azkaban ","J.K Rowling","1998"),
(3,"harry potter and the half blood prince","J.K Rowling","2007"),
(6,"Harry potter and deathly hallows","J.K Rowling","2010"),
(8,"The secret","someone","2009")]
print findBook(L, "harry")
Output:
[(2, 'harry potter and the prisoner of azkaban ', 'J.K Rowling', '1998'), (3, 'harry potter and the half blood prince', 'J.K Rowling', '2007')]
Notice the third entry was not found because the keyword
is "harry" and not "Harry", to do insensitive case search, use:
def findBook(L, keyword):
books = list()
keyword = keyword.tolower()
for book in L:
book = tuple(entry for entry in book)
if [i for i in book if str(i).tolower().find(keyword) != -1]:
books.append(book)
return books
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.