首页 > 解决方案 > 如何在文本文件中搜索某些内容并在 python 中输出它的详细信息?

问题描述

我的程序的目的是显示一个菜单,让您能够添加新的“书”,其中包含作者、价格和副本等详细信息到文本文件。程序的第二部分应要求用户输入作者姓名,然后程序必须在文本文件中查找该作者的姓名并显示与该作者相关的书籍、价格和副本。我的问题是我不确定如何做第二部分。“行”分为 4 个部分,作者、书籍、价格和副本。作者16个字,书20个字,价格5个,份数2个。假设作者是JK罗琳,也就是12个字,我有个函数加“”(空格)来满足16个条件. 所有部门也是如此。到最后让' s 说它是 JK 罗琳哈利波特书 2 12.9912。作者:“JK Rowling” 书籍:“Harry Potter Book 2” 价格:“12.99” 份数:“12” 从技术上讲,这就是对第一部分的解释。第二部分应该搜索“JK Rowling”然后得到结果:

作者:《JK罗琳》书籍:《哈利·波特第2册》价格:“12.99”份数:“12”

如果有比这更有效的方法,那么将不胜感激,但现在第 2 部分是主要问题。

ps 必须通过文本文件来完成

完整程序(第 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])

标签: pythonpython-3.xpython-2.7menutext-files

解决方案


这是处理第 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

推荐阅读