【问题标题】:How can I search for a string inside a .txt file and print the line where the string is in? (Python)如何在 .txt 文件中搜索字符串并打印字符串所在的行? (Python)
【发布时间】:2020-11-24 18:46:36
【问题描述】:

上面的问题。我正在尝试在 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()

希望你能理解我的问题。

【问题讨论】:

  • 您好,您是否检查过此 [链接][1],我相信它可以回答您的问题或可能会有所帮助。 [1]:thispointer.com/…

标签: python python-3.x text printing console


【解决方案1】:

原始 sn-p 的略微修改版本:

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 函数来获取运行索引和行号,以后可以将其用作行号。

将所有这些放在一起后,您基本上可以随心所欲地增强查找逻辑。

【讨论】:

    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    相关资源
    最近更新 更多