Python 如何搜索文本文件并返回包含用户输入字符串的所有项目

Python 如何搜索文本文件并返回包含用户输入字符串的所有项目,python,string,python-3.x,Python,String,Python 3.x,文本文件的每一行都按字母顺序列出所有畅销书的书名、作者、出版商、日期和流派。我希望能够按作者或标题搜索此文本文件,以便能够打印包含已输入字符串的作者的所有书籍(“作者的书籍名称”) def author_search(): author_string = input('Enter a title') lower_author = author_string.lower() with open('file.txt', 'r') as book_file: f

文本文件的每一行都按字母顺序列出所有畅销书的书名、作者、出版商、日期和流派。我希望能够按作者或标题搜索此文本文件,以便能够打印包含已输入字符串的作者的所有书籍(“作者的书籍名称”)

def author_search():
    author_string = input('Enter a title')
    lower_author = author_string.lower()
    with open('file.txt', 'r') as book_file:
        for line in book_file:
            if 'lower_title' in line:
                print(line)


def title_search():
    title_string = input('Enter a title')
    lower_title = title_string.lower()
    with open('file.txt', 'r') as book_file:
        for line in book_file:
            if 'lower_title' in line:
                print(line)
我没有得到任何错误,但当我用我的主函数运行它时,我也没有得到任何输出

def main():
    run = True
    while run:
        book_file = open('file.txt', 'r')
        print('What would you like to do? ')
        print('1: Look up year range')
        print('2:Look up month/year')
        print('3:Search for author')
        print('4:Search for title')
        print('Q: Quit')
        userOp = input('Select an operation by entering its number: ')
        book_file = open('file.txt', 'r')
        if userOp == 1:
            print(year_range(book_file))
        if userOp == 2: 
            print(month_year(book_file))
        elif userOp == 3:
            print(author_search(book_file))
        elif userOp == 4:
            print(title_search(book_file))
     runCheck = input('Do you want to run another operation? ')
        if runCheck.lower == 'Q':
            run = False
            print('Goodbye')
它要求我选择和操作,然后立即询问我是否要运行另一个操作

A Dance With Dragons    George R. R. Martin Bantam   7/31/2011   Fiction
A Day Late and a Dollar Short   Terry McMillan  Viking  2/4/2001    Fiction
A Feast For Crows   George R. R. Martin Bantam  11/27/2005  Fiction
A Lion Is In the Streets    Adria Locke Langley McGraw  7/1/1945    Fiction
A Man In Full   Tom Wolfe   Farrar, Straus & Giroux 11/22/1998  Fiction

首先,您的
main()
函数中有一个语法错误;在
book\u file=open(file.txt,,'r')
中有一个不合适的
另外,请发布几行文本文件,这样我们就可以理解语法了……另外,
如果行中的'lower\u title':
应该是
如果行中的'lower\u title:
如果行中的'lower\u author:
。您告诉Python查找字符串
'lower\u title'
,而不是用户输入。我添加了其中的一些。您有两个函数,两个函数的作用完全相同。要么让它成为一个简单的“search_any”函数,只查找字符串,要么让它成为一个区分作者和标题的解析器。