对于我要设计的程序,我正在检查配置文件中是否存在某些条件。例如,以下行:ThisExists在程序中,或者ThisIsFirst存在于文件中,其后是ThisAlsoExists,位于文件的后面。
我正在寻找一种可以在这种情况下使用但找不到任何方法的有效方法。
我目前的想法基本上是每次我要检查条件时都多次遍历文件。因此,我将具有以下功能:
def checkA(文件)
def checkB(文件)
。。。
对我来说,这似乎效率很低,因为我必须针对要检查的每个条件进行迭代。
最初,我认为我可以重复一次,检查每一行以确认要验证的每种条件。但是我不认为我能做到这一点,因为可能是多行的条件一次需要有关多个行的信息。
我概述的方法是执行此操作的唯一方法,还是有一种更有效的方法?
我正在尝试在下面提供一个示例。
def main():
file = open(filename)
result1 = checkA(file)
result2 = checkB(file)
"""This is a single line check function"""
def checkA(file)
conditionExists = False
for line in file:
if(line == "SomeCondition"):
conditionExists = True
return conditionExists
"""This is a multi line check function"""
def checkB(file)
conditionExists = False
conditionStarted = False
for line in file:
if(line == "Start"):
conditionStarted = True
elif(line == "End" and conditionStarted):
conditionExists = True
return conditionExists
如果可用的库(configparser等)还不够,我可能会使用正则表达式。
import re
check_a = re.compile('^SomeCondition$', flags=re.MULTILINE)
check_b = re.compile('^Start(?:.|\n)*?End$', flags=re.MULTILINE)
def main(file_name):
with open(file_name, 'r') as file_object:
file_content = file_object.read()
result_1 = bool(check_a.search(file_content))
result_2 = bool(check_b.search(file_content))
这不是最用户友好的方法,尤其是在匹配条件复杂的情况下,但是我认为学习正则表达式的收益是巨大的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句