如何在文本文件中搜索内容并将其详细信息输出到 python?

How can I search for something in a text file and output it's details in python?

我的程序的目的是显示一个菜单,使您能够添加新的 "Book" 及其详细信息,例如作者、价格和文本文件的副本。程序的第二部分应该要求用户输入作者姓名,然后程序必须在文本文件中查找该作者的姓名并显示与该作者相关的书籍、价格和副本。我的问题是我不确定如何将第二个 part.A "line" 分为 4 个部分,作者、书籍、价格和份数。作者有 16 个字符,书籍有 20 个字符,价格有 5 个字符,副本有 2 个字符。假设作者是 J.K。罗琳,那是12个字符,我有一个功能,添加“”(空格)以满足它是16的条件。所有部门都一样。到它结束时,假设它是 J.K。罗琳哈利波特书 2 12.9912。 作者:"J.K. Rowling " 书:"Harry Potter Book 2 " 价格:“12.99” 份数:“12” 这就是第一部分的技术解释。第二部分应该搜索"J.K. Rowling",然后得到的结果是:

作者:"J.K. Rowling " 书:"Harry Potter Book 2 " 价格:“12.99” 份数:“12”

如果有比这更有效的方法,我们将不胜感激,但目前第 2 部分是主要问题。

p.s。必须通过文本文件完成

完整程序(第 1 部分作品):

def AddSpaces(auth,numb):
    print("Runs")
    while len(auth) < numb:
        auth = auth + " "
    return (auth)



menu = 1
while menu <= 2:
    menu = int(input("1. Add a new book\n2. Search for a new book by a given author\n3. End"))
    if menu ==1:

        BOOKS = open("BOOKS.txt","a")

        Author = str(input("Author: "))
        if len(Author) < 16:
            Author = AddSpaces(Author,16)
        while len(Author) > 16:
            Author = str(input("Author: "))
            Author = AddSpaces(Author,16)
        print(Author)

        Book = str(input("Book: "))
        if len(Book) < 20:
            Book = AddSpaces(Book,20)
        while len(Book) > 16:
            Book = str(input("Book: "))
            Book = AddSpaces(Book,20)
        print(Book)

        Price = str(input("Price: "))
        while len(Price)>5:
            Price = str(input("Price: "))

        Copies = str(input("Copies: "))
        while len(Copies)>2:
            Copies = str(input("Copies: "))

        line = Author + Book + Price + Copies +"\n"
        print(line)
        BOOKS.write(line)
        BOOKS.close()


    elif menu == 2:
        BOOKS = open("BOOKS.txt","r")
        while True:
            AuthorSearch = str(input("Author name for search: "))
            if len(AuthorSearch) < 16:
                AuthorSearch = AddSpaces(AuthorSearch,16)
            while len(AuthorSearch) > 16:
                AuthorSearch = str(input("Author name for search: "))
                AuthorSearch = AddSpaces(AuthorSearch,16)
            print(AuthorSearch)

            n = BOOKS.read()
            if n == "":
                print("End of file, no books found")
                break
            if AuthorSearch == line[:16]:
                print ("Author found.")
                print ("Author name: ") + (line[:16])
                print ("Book name: ") + (line[17:36])
                print ("Price: ") + (line[37:41])
                print ("Copies: ") + (line[42:43])

这是处理第 1 部分和第 2 部分的代码的简单修改

模组基于以下内容

  1. 使用Python变量命名约定Pep 8
  2. 使用制表符分隔行以避免必须使用固定字段 宽度
  3. 使用 lower() 提供不区分大小写的比较
  4. 使用字符串title() 确保每个单词的首字母大写表示作者 和书名

重构代码

while True:
  menu = input("1. Add a new book\n2. Search for a new book by a given author\n3. End\n")
  if menu in ('1', '2', '3'):
    menu = int(menu)
  else:
    print('Error -- Menu needs to be 1, 2, or 3')
    continue

  if menu == 1:
      author = input("Author: ")
      book = input("Book: ")
      price = input("Price: ")
      copies = input("Copies: ")

      line = '\t'.join([author.title(), book.title(), price, copies])
      with  open("BOOKS.txt","a") as books:
        print(line)
        books.write(line + "\n")

  elif menu == 2:
      author_search = input("Author name for search: ")
      if not author_search:
        print("Need author's name")
        continue  # quit on blank line for author

      author_search = author_search.lower()
      with open("BOOKS.txt","r") as books:
        found = False
        for line in books:
          # Will print all books by this author
          book_info = line.rstrip().split("\t")

          if author_search == book_info[0].lower(): # use lower to make case insensitive match
            found = True
            print('>>> Found Author')
            author, bookname, price, copies = book_info
            print(f'Author name: {author.title()}') # capitable firs letter of each name
            print(f'Book: {bookname.title()}')
            print(f'Price: {price}')
            print(f'Copies: {copies}')
        if not found:
          print('Author not found')
  else:
    break