【问题标题】:how to find a substring from a particular row of a file in python [duplicate]如何从python中文件的特定行中查找子字符串[重复]
【发布时间】:2021-12-11 18:34:19
【问题描述】:

我正在尝试读取包含数百个名称的 .txt 文件,并且我想查找特定名称。

例如,我有几个类似的名字

John simons
kumar ayush singh
peter calpidi
david brown

等,我想寻找一个子字符串 ayush 如果子字符串存在我想返回完整的字符串,如kumar ayush singh

我尝试过这样的事情:

try:
    with open('D:\\Any One\\name_list.txt') as names:
        for row in names:
            if row.find(request.strip()) != -1:
               results = row
               print(row)
except Exception as err:
    print(err)

但出现错误:

'charmap' codec can't decode byte 0x81 in position 4467: character maps to undefined

【问题讨论】:

    标签: python file


    【解决方案1】:

    参考号:https://docs.python.org/3.9/library/functions.html#open

    查看您喜欢的错误选项。在代码中,我放了replace,因为它会在发生错误的地方放一个标记并继续处理文件。

    try:
        with open('D:\\Any One\\name_list.txt',errors='replace') as names:
            for row in names:
                if row.find(request.strip()) != -1:
                   results = row
                   print(request)
    except Exception as err:
        print(err)
    

    【讨论】:

    • 它现在没有显示错误。但由于某种原因它仍然没有将名称作为字符串返回?猜猜为什么??
    • 这可能是因为 find 方法。我的意思是我不经常使用它,所以它在这里可能没用..??
    • 好像要打印(请求)
    • 修复了它。谢谢
    • 如果解决了问题,请接受我的回答。
    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    相关资源
    最近更新 更多