繁体   English   中英

Python-搜索字符串是否在文件中

[英]Python - searching if string is in file

我想在文件中搜索字符串,如果有字符串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

如果没有那个字符串,它就可以正常工作,但是,如果有那个字符串,我在搜索它的内容将导致找不到动作。 我真的不知道如何解决它,我已经尝试过其他站点的一些代码,但是在我的代码中它不起作用。 有人可以帮忙吗?

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

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

如果是这样,则只需要在此语句下面的代码块中添加以下内容:

found = True

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM