【问题标题】:Python readlines string issuePython readlines字符串问题
【发布时间】:2014-03-24 09:12:04
【问题描述】:
import os
fname = "input1.txt"

if os.path.isfile(fname):
        f = open("input1.txt", "r")

    for row in f.readlines():
            if "logging failed" in row:
                    print "the file does say 'logging failed' in it"
            else:
                    print "the file doesn\'t say 'logging failed' in it"

我的input1.txtlogging failedtest 那么我怎样才能让它注意到“测试”,以便它只在文本没有任何其他字符的情况下打印输出日志记录失败?

编辑: 抱歉英语不好,我的意思是:如果 input1.txt 只有“记录失败”,那么它应该打印出“文件确实说”。如果它有任何其他字符(例如'logging faaaailed'或'logging failed1',那么它应该打印出'it doesn't say logging failed'。现在它只是读取记录失败并忽略输入中的任何其他字符1 .txt

【问题讨论】:

  • 有点不清楚你在问什么。问题是它说logging failedtest 被报告为其中包含logging failed,还是您多次报告的问题,每行一次?
  • if row.rstrip() == 'logging failed'
  • 抱歉英语不好,我的意思是:如果 input1.txt 只有“记录失败”,那么它应该打印出文件确实说。如果它有任何其他字符(例如'logging faaaailed'或'logging failed1',那么它应该打印出它没有说日志记录失败。现在它只是读取日志记录失败并忽略input1.txt中的任何其他字符

标签: python string substring readlines


【解决方案1】:

也许我遗漏了一些东西,但你为什么不能明确地将 row 与字符串 "logging failed" 进行比较?

例如。 if row == "logging failed"

【讨论】:

  • 我也是这么想的
  • 我将 input1.txt 更改为只是“记录失败”和我的 if row ==“记录失败”的代码,但现在它打印了后者(文件没有说...)?
【解决方案2】:

您可以尝试以下方法:

if row.find('logging') != -1 and row.endswith('failedtest'):

【讨论】:

    【解决方案3】:

    试试这个row.count("logging failed") > 0

    import os
    fname = "input1.txt"
    
    if os.path.isfile(fname):
            f = open("input1.txt", "r")
    
        for row in f.readlines():
                if row.count("logging failed") > 0:
                        print "the file does say 'logging failed' in it"
                else:
                        print "the file doesn\'t say 'logging failed' in it"
    

    样本测试:

    In [4]: t = "the file does say 'logging failed' in it"
    
    In [5]: t.count('logging failed')
    Out[5]: 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2014-01-08
      • 2011-01-24
      • 2012-02-22
      相关资源
      最近更新 更多