Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python从文本文件中列出具有特定体裁的书籍标题_Python - Fatal编程技术网

使用Python从文本文件中列出具有特定体裁的书籍标题

使用Python从文本文件中列出具有特定体裁的书籍标题,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 , "

我一直在尝试输出所有这类书籍的标题。这是迄今为止的代码:

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):


你想过使用正则表达式吗?每本书的条目都由标题、体裁和页数组成。制作一个表达式来捕获这些内容并匹配类型查询

重新导入
query=“Horror”#输入(“您要找哪种类型的书?”)
打开(“books.txt”、“r”)作为fh:
regex=re.compile(f“(?P.+?)\n{query}\n(?P\d*)”)
数据=fh.read()
结果=re.findall(正则表达式,数据)
对于结果中的结果:
title,num=结果
印刷品(标题)
或者将所有书籍添加到字典中,然后进行筛选:

重新导入
query=“Horror”#输入(“您要找哪种类型的书?”)
书籍=[]
打开(“books.txt”、“r”)作为fh:
regex=re.compile(f“(?P.+?)\n(?P.+?)\n(?P\d*))
数据=fh.read()
结果=re.findall(正则表达式,数据)
对于结果中的结果:
标题、类型、数量=结果
书。附加({
“标题”:标题,
“页面”:num,
“体裁”:体裁
})
结果=[book['title']对于books in books if book['流派']==query]
打印(结果)
#[‘第一册’、‘第七册’]

您的代码中有一些输入错误,如果您想使用相同的代码,解决方法是:

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": [
    {},
    {}
  ]
}

使用
文件[query]
可以非常快速地访问数据。希望这有帮助

我希望你已经学习了
词典。这里真的很方便。
{
  "Horror": [
    {
      "name": "Book one",
      "cost": "300"
    },
    {
      "name": "Book seven",
      "cost": "150"
    }
  ],
  "Mystery": [
    {},
    {}
  ],
  "Fantasy": [
    {},
    {}
  ]
}