简体   繁体   English

如何在 .txt 文件中搜索字符串并打印字符串所在的行? (Python)

[英]How can I search for a string inside a .txt file and print the line where the string is in? (Python)

Question above.上面的问题。 I'm trying to create a contact book inside of the console in Python 3, and i'm trying to implement a "search" command, but everything i've tried didn't work.我正在尝试在 Python 3 的控制台内创建一个通讯录,并且我正在尝试实现一个“搜索”命令,但是我尝试过的所有方法都不起作用。 I didn't find anything helpful on the internet either.我也没有在互联网上找到任何有用的东西。

f = open("C:/Users/Yonas/Documents/PythonProject.txt", "a")
entry = input()
i = 0

def add():
    print("Please type in the name of the person you want to add.")
    in2 = input()
    f.write(in2 + " | ")

    print("Please type in the location of the person you want to add.")
    in3 = input()
    f.write(in3 + " | ")

    print("Please type in some additional information.")
    in4 = input()
    f.write(in4 + "\n")

def search():
    line_number = 0
    print("Please type in the name of the person you're looking for.")
    inSearch = input()
    list_of_results = list(f)
    
    # The code should be here

if entry.startswith("add"):
    add()

if entry.startswith("search"):
    search()

Hope you understand my problem.希望你明白我的问题。

A slightly reworked version of your original snippet:对原始代码段稍加修改的版本:

contact_book_path = "collection.txt"


def add():
    with open(contact_book_path, "a") as contact_book_fp:
        contact = ""

        name = input("Please type in the name of the person you want to add.\n")
        contact += name + " | "

        location = input("Please type in the location of the person you want to add.\n")
        contact += location + " | "

        info = input("Please type in some additional information.\n")
        contact += info + "\n"

        contact_book_fp.write(contact)


def search():

    with open(contact_book_path, "r") as contact_book_fp:
        name_search = input(
            "Please type in the name of the person you're looking for.\n"
        )

        for line_no, contact in enumerate(contact_book_fp.readlines()):
            name, location, info = contact.split(" | ")

            if name == name_search:
                print("Your contact was found at line " + str(line_no))
                return

        print("Your contact was not found! :(")


entry = input("What kind of operation would you like to do (add/search)?\n")
if entry.startswith("add"):
    add()

if entry.startswith("search"):
    search()

Instead of having the file open in and in append mode, I'd suggest you to open it for the right operation when you really need it.与其在追加模式下打开文件,不如建议您在真正需要时打开它以进行正确的操作。 So for appending in add and for reading in search .因此,对于附加在add和在search阅读。

In the search function after opening the file and asking for the name to search for, you can use the standard file.readlines() method to iterate through the lines in a file.search打开文件,并要求将名称搜索功能后,您可以使用标准file.readlines()通过在一个文件中的行方法进行迭代。 Also I used the enumerate function to get a running index together with a line, and I can use it as the line number later on.我还使用enumerate函数将运行索引与行一起获取,稍后我可以将其用作行号。

Having put all these together, you can basically enhance the lookup logic any way you want.将所有这些放在一起后,您基本上可以以任何您想要的方式增强查找逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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