【问题标题】:How to search for a string in a file in python? [duplicate]如何在python中搜索文件中的字符串? [复制]
【发布时间】:2017-07-14 02:57:59
【问题描述】:

我在文件中搜索字符串,但即使文件中有匹配的字符串,它总是返回 false。我哪里错了?

file = open('temp.txt', 'r')

def search(userinput, file):

    file.seek(0)
    filecontent = file.readlines()
    for i in filecontent:
        sp = i.split(' ')
        t_name = sp[0] + ' ' + sp[1]
        print (t_name)
    if (t_name == userinput):
        return True
    else:
        return False


searchstr = 'Peter Piper'
found = search(searchstr, file)
print (found)
file.close

temp.txt

Peter Piper 20 30
Tom Cat 10 20
Jerry Mouse 30 50

【问题讨论】:

  • 建议的问题和解决方案似乎与我的完全不同。我在 if 条件下遇到缩进问题,如果我将它包含在 for 循环下,它只检查第一行,如果我没有将它包含在 for 循环下,如上所示,它似乎总是返回 false。

标签: python python-3.x


【解决方案1】:

为了与您用来解释具体问题所在的代码示例保持同步...

您的问题是,您实际上只是在 for 循环运行后检查 t_name 是否是用户输入。你想做的就是这个

Peter Piper 20 30
Tom Cat 10 20
Jerry Mouse 30 50




file = open('temp.txt', 'r')

def search(userinput, file):

    file.seek(0)
    filecontent = file.readlines()
    for i in filecontent:
        sp = i.split(' ')
        t_name = sp[0] + ' ' + sp[1]
        print (t_name)
        if (t_name == userinput):
            return True
    return False


searchstr = 'Peter Piper'
found = search(searchstr, file)
print (found)
file.close

在我的代码示例中,每次 for 循环运行时,它都会检查名称是否匹配,如果匹配,则结束函数并返回 True。如果它从不结束函数并在 for 循环结束之前返回 True,这意味着没有一个名称是匹配的,它应该在 for 循环完成后返回 False

【讨论】:

  • 成功了。非常感谢..我知道这是一个缩进问题,但无法完全找到解决方案。再次感谢:) @Mark R
【解决方案2】:

你可以试试这个:

f = open('filename.txt').readlines()

f = [i.strip('\n') for i in f]

word = 'Peter Piper'
if any(word in i for i in f):
    print "word exists in file"

【讨论】:

  • 为什么不直接遍历文件:for line in open('filename.txt'),然后将word 与每个lineif word in line: 进行比较?此外,最好在打开文件时使用上下文管理器,因为它可以确保您的文件始终处于关闭状态。
【解决方案3】:

问题是您正在检查外部循环,其中t_nameJerry Mouse,这是最后一个值,应该是这样的

file = open('temp.txt', 'r')

def search(userinput, file):
    file.seek(0)
    filecontent = file.readlines()
    for i in filecontent:
        sp = i.split(' ')
        #print(sp)
        t_name = sp[0] + ' ' + sp[1]
        print (t_name)
        if (t_name == userinput):
            return True
    return False


searchstr = 'Peter Piper'
found = search(searchstr, file)
print (found)
file.close

【讨论】:

    猜你喜欢
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多