Python 提取文本文件中两行字符串之间的行
我有以下示例文本文件(其格式如下所示)。我想提取“生成配置…”和“`show accounting log all`”这两行之间的所有内容,这是我感兴趣的内容的开始和结束 一些行Python 提取文本文件中两行字符串之间的行,python,Python,我有以下示例文本文件(其格式如下所示)。我想提取“生成配置…”和“`show accounting log all`”这两行之间的所有内容,这是我感兴趣的内容的开始和结束 一些行 再来一行 正在生成配置 感兴趣的配置 感兴趣的配置 感兴趣的配置 `显示所有记帐日志` 一些行 再来一行 我编写了以下代码,但在找到“showcounting log all”后,它并没有停止向文本文件追加行 config_found = False with open(filename, 'rb')
再来一行
正在生成配置
感兴趣的配置
感兴趣的配置
感兴趣的配置
`显示所有记帐日志`
一些行
再来一行
我编写了以下代码,但在找到“showcounting log all”后,它并没有停止向文本文件追加行
config_found = False
with open(filename, 'rb') as f:
textfile_temp = f.readlines()
for line in textfile_temp:
if re.match("Generating configuration....", line):
config_found = True
if re.match("`show accounting log all`", line):
config_found = False
if config_found:
i = line.rstrip()
textfile.append(i)
我的陈述有什么错
config\u found
似乎在循环之外没有作用域
将
config\u found=False
放在循环之前,它应该可以正常工作。在比较中必须使用反引号,并且可以使用if和elif在字符串之间提取。我已修改如下,并且它正在工作:
with open('file.txt', 'rb') as f:
textfile_temp = f.readlines()
config_found = False
textfile = []
for line in textfile_temp:
if re.match("`show accounting log all`", line):
config_found = False
elif config_found:
i = line.rstrip()
textfile.append(i)
elif re.match("Generating configuration....", line):
config_found = True
print textfile
输出:
['interested config', 'interested config', 'interested config']
interested config
interested config
interested config
相反,您可以按如下方式使用拆分:
with open('file.txt', 'rb') as f:
textfile_temp = f.read()
print textfile_temp.split('Generating configuration....')[1].split("`show accounting log all`")[0]
输出:
['interested config', 'interested config', 'interested config']
interested config
interested config
interested config
在您的示例内容中,它们是围绕
show accounting log all
的反勾号,而在您的代码中它是在查找单引号,因此它永远不会匹配。(为什么要使用regex模块re,而不是普通的字符串比较?)!我的原始代码中的if语句有什么问题(我已经修复了backticks,但仍然失败了)?我似乎不明白为什么它不起作用。在更改配置变量之后,您正在加载结果变量。应该扭转这种局面。