查找在Python中搜索的字符串的行号

时间:2013-03-22 05:49:52

标签: python string search

    def c1():
        logfile = open("D:\myfile.txt", 'r')
        for num1, line in enumerate(logfile):
                if "request=100" in line:
                    print num1
                    return True
        return False

    def c2():
        logfile = open("D:\myfile.txt", 'r')
        for num2, line in enumerate(logfile):
                if "response=200" in line:
                    print num2
                    return True
        return False    

    if c1() == True and c2() == True:
        print "Test Case Passed"  
    else:
        print "Test Case Failed"

在上面的代码中,检查行号以使request = 100和response = 200将不在同一行。我需要的。

另外,我希望仅在满足以下条件时才将结果打印为“通过”...

- both c1 and c2 are True
- both "request=100" and "response=200" should fall in same line 
- if any other line also consist of "request=100" and "response=200" then that also should be counted

如果出现以下情况,结果为“失败”:

- if any one line which consists of "request=200" and "response=200"
- if any one line which consists of "request=100" and "response=100" 
- or any case in which no line should have apart from "request=100" and "response=200"

考虑“myfile”有以下数据:

request=100 XXXXXXXXXXXXXXXXXXXXXXXXXXXX \n
XXXXXXXXXXXXXXXX response=200 XXXXXXXXX \n
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \n
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \n
XXXX request=100 XXXXX response=200 XXXXXXXXXXX \n
XXXXXXX request=200 XXXXXX response=100 XXXXXXX \n
XXXXXXXX request=100 XXXX response=100"         \n

在上面的文件中,结果为Fail,因为请求和响应具有与所需值不同的值。只有第5行具有正确的值,因此结果失败。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你应该将两个条件放在一个循环中,并保持循环直到你到达行的末尾,或者遇到另一行条件:

def are_they_on_the_same_line():
    logfile = open("D:\myfile.txt", 'r')
    intermediate_result = False
    for num1, line in enumerate(logfile):
            if "request=100" in line and "response=200":
                if intermediate_result == True:
                    return False
                intermediate_result = True
    return intermediate_result

除了您提到的失败条件外,还有其他条件失败。但你提到的两个并不是相互排斥的。

编辑:从这个例子来看,不要等待这是错的。我无法理解你的情况。也许它可以帮助你获得一个想法,如果没有,请用另一个例子澄清条件。