在Python中查找字符串的行号
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的情况就会在同一行中。我需要这个检查。
另外,只有在满足以下条件时,我想把结果打印为“通过(Pass)”……
- 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
如果结果是“失败(Fail)”的话:
- 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
在上面的文件中,结果是失败,因为请求和响应的值与要求的值不同。只有第5行的值是正确的,因此结果是失败。
1 个回答
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
除了你提到的失败条件,还有其他情况会导致这个方法失效。不过你提到的这两个条件并不是互相排斥的。
编辑:等一下,这样说不对,从例子来看。我无法理解你的条件。如果你能提供另一个例子,可能会帮助我更好地理解你的意思,如果没有,请再解释一下条件。