首页 > 解决方案 > 如何在 .txt 文件中搜索字符串并打印字符串所在的行?(Python)

问题描述

上面的问题。我正在尝试在 Python 3 的控制台内创建一个通讯录,并且我正在尝试实现一个“搜索”命令,但我尝试过的一切都没有奏效。我也没有在互联网上找到任何有用的东西。

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

希望你能理解我的问题。

标签: pythonpython-3.xtextprintingconsole

解决方案


原始片段的略微修改版本:

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

我建议您在真正需要时打开它以进行正确的操作,而不是在附加模式下打开文件。因此,对于附加add和读取search.

search打开文件并要求搜索名称后的函数中,您可以使用标准file.readlines()方法遍历文件中的行。我还使用该enumerate函数将运行索引与行一起获取,以后可以将其用作行号。

将所有这些放在一起,您基本上可以以任何您想要的方式增强查找逻辑。


推荐阅读