在文本文件Python中搜索特定单词

时间:2018-02-10 17:10:49

标签: python search text-files

我一直在创建一个程序,用于编目和查找我从python到文本文件的书籍。首先,它会为您提供所有书籍的列表(我将在以后按字母顺序排序)然后询问您是否要添加任何书籍,然后将标题和作者添加到文本文件中。然而,我的问题是,之后我本来可以选择搜索书籍或作者,然后输入书名或作者,它应该搜索文本文件并打印出每行都带有关键字输入它。

我已经查看了多个论坛和教程,以了解如何执行此操作,但似乎没有一个有效。

到目前为止我的代码:

import time
import random

x = 2

file = open("bookList.txt", "r")
print(file.read())
file.close()

addBookYorN = input("Do you want to add a book to the list? \n")

if addBookYorN in ["Y", "y", "Yes", "yes"]:

while x > 1:
    addBookName = input("Book: ")
    addBookAuthor = input("Author: ")

    file = open("bookList.txt", "a")
    file.write(addBookName + " - ")
    file.write(addBookAuthor + "\n")
    file.close()

    stahp = input("Do you want to add another book? \n")

    if stahp in ["No", "no", "N", "n"]:
        x = x - 1

elif addBookYorN in ["N", "n", "No", "no"]:
    print("Okay")

bookSearchYorN = input("Do you want to find a book or author? \n")

if bookSearchYorN in ["Y", "y", "Yes", "yes"]:
    file = open("bookList.txt", "r")
    bookSearch = input("What book or author are you looking for? \n")

1 个答案:

答案 0 :(得分:1)

如果您想使用搜索输入打印出每一行,您可以这样做。

bookSearch = input("What book or author are you looking for? \n")
with open("bookList.txt", r) as infile:
    for line in infile.readlines():
        if bookSearch in line:
            print(line)

当您写入文件时:

<强>替换

file = open("bookList.txt", "a")
file.write(addBookName + " - ")
file.write(addBookAuthor + "\n")
file.close()

<强>与

with open("bookList.txt", "a") as infile:
    infile.write(addBookName + " - " + addBookAuthor + "\n")

这有助于归还特定作者撰写的所有书籍。