[英]Searching for specific words in text file Python
我一直在創建一個程序,用於對從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")
如果您想用搜索輸入打印出每一行,則可以執行。
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")
這可以幫助歸還由特定作者撰寫的所有書籍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.