简体   繁体   English

返回具有共同“关键字”的书籍的元组

[英]Returns tuples of books that have a “keyword” in common

I have a database saved as a list of tuples, and every tuple has 4 elements. 我有一个保存为元组列表的数据库,每个元组都有4个元素。 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. 我需要一个名为findBook(L, keyword)的函数findBook(L, keyword)该函数接收作为元组列表的书籍,作为字符串的keyword ,并返回其中包含keyword所有tuples of books The tuple of the book should be like this: tuple of the booktuple of the book应该是这样的:

(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. 因此,如果我有一本哈利·波特书,并且输入关键字:“ harry”,它应该返回整个元组。

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: 您可以遍历可能具有您要查找的keyword的条目,将它们分组到一个列表中,该列表将在过程结束时返回:

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: 请注意,未找到第三个条目,因为keyword是“ harry”而不是“ Harry”,因此要进行不区分大小写的搜索,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM