首页 > 解决方案 > 使用 Python 从文本文件中列出具有特定类型的书名

问题描述

我一直在尝试输出所有具有该类型的书名。这是到目前为止的代码:

query = input("Books from which genre are you looking for? ")
file = open("books.txt","r")
counter2 = 1
n = 0
lines = file.readlines()
for line in file:
  if query in line:
    counter2 += 1
    n += 2
print(counter2 , " - " , lines[n])
file.close()

但是,它只输出一个标题。我希望它输出该类型的所有书籍。

这是文本文件(books.txt):

Book one
Horror
300
Book two
Fantasy
150
Book three
Mystery
400
Book four
Romance
100
Book five
Fantasy
600
Book six
Fantasy
90
Book seven
Horror
150

标签: python

解决方案


您的代码中有一些错字,如果您想使用相同的代码,修复方法是:

query = input("Books from which genre are you looking for? ")
file = open("books.txt","r")
counter2 = 0
n = 0
lines = file.readlines()
for line in lines:
  if query in line:
    counter2 += 1
    print(counter2 , " - " , lines[n-1])
  n += 1
file.close()

并且可以进行许多优化,例如仅迭代包含该类型的行。此外,如果您手头有数据,您可以将 book.txt 转换为字典,例如,

{
  "Horror": [
    {
      "name": "Book one",
      "cost": "300"
    },
    {
      "name": "Book seven",
      "cost": "150"
    }
  ],
  "Mystery": [
    {},
    {}
  ],
  "Fantasy": [
    {},
    {}
  ]
}

您将使用 非常快速地访问数据file[query]。希望这可以帮助!


推荐阅读