【问题标题】:Python - searching if string is in filePython - 搜索字符串是否在文件中
【发布时间】:2014-05-19 17:09:53
【问题描述】:

我想在文件中搜索字符串,如果有字符串 make 动作,如果没有字符串 make 其他动作,但是从这个代码:

    itcontains = self.textCtrl2.GetValue()
    self.textCtrl.AppendText("\nTY: " + itcontains)
    self.textCtrl2.Clear()
    pztxtflpath = "TCM/Zoznam.txt"
    linenr = 0
    with open(pztxtflpath) as f:
        found = False
        for line in f:
            if re.search("\b{0}\b".format(itcontains),line):
                hisanswpath = "TCM/" + itcontains + ".txt"
                hisansfl = codecs.open(hisanswpath, "r")
                textline = hisansfl.readline()
                linenr = 0
                ans = ""
                while textline <> "":
                    linenr += 1
                    textline = hisansfl.readline()
                hisansfl.close()
                rnd = random.randint(1, linenr) - 1
                hisansfl = codecs.open(pztxtflpath, "r")
                textline = hisansfl.readline()
                linenr = 0
                pzd = ""
                while linenr <> rnd:
                    textline = hisansfl.readline()
                    linenr += 1
                ans = textline
                hisansfl.close()
                self.textCtrl.AppendText("\nTexter: " + ans)
        if not found:
            self.textCtrl.AppendText("\nTexter: " + itcontains)
            wrtnw = codecs.open(pztxtflpath, "a")
            wrtnw.write("\n" + itcontains)
            wrtnw.close

如果没有那个字符串,它就可以正常工作,但是如果有那个字符串,我正在搜索的内容会在未找到时执行。我真的不知道如何修复它,我已经尝试了其他网站的一些代码,但在我的代码中它不起作用。有人可以帮忙吗?

【问题讨论】:

    标签: python string search wxpython


    【解决方案1】:

    您是说如果字符串包含您要查找的内容,则执行以下 if 语句下的代码?

     if re.search("\b{0}\b".format(itcontains),line):
    

    如果是这样,那么您只需在该语句下方的代码块中添加以下内容:

    found = True
    

    这将使您的 if not found 子句无法运行。如果您要查找的字符串只能找到一次,我还会在您的第一个语句中添加一个 break 语句以跳出循环。

    【讨论】:

    • 非常感谢您的回答!我只是在用那个代码做一些事情,所以发现 = True 在那里,谢谢你的提示(中断),是的,我发现错误可能在 if re.search...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多