繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM