python - 使用 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
解决方案
您的代码中有一些错字,如果您想使用相同的代码,修复方法是:
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]
。希望这可以帮助!
推荐阅读
- c# - 如何禁止在新窗口中禁用打开页面 - cefsharp
- windows - 在子文件夹中搜索请求的文件并复制到目标
- java - 从scrapy中的lst刮掉链接或创建一个循环?
- javascript - 如何从 url 获取查询并将其发送到 nuxt js 项目的 Store
- c# - 如何在一个 ImageProcessor.Web 请求中应用多个“过滤器”?
- flutter - Flutter - 在执行 .then 之前,函数返回值,然后读取 .then
- python - 如何从位于3索引倍数的列表中获取所有数字
- python - 使用xpath selenium python获取子元素
- c# - 如何在通用存储库中的 linq 中添加包含属性的位置?
- ios - cordova-plugin-local-notification 触发器在 IOS 中不起作用