【发布时间】:2015-02-05 13:50:47
【问题描述】:
我有一个文本文件,其中包含一些格式,例如:
PAGE(leave) 'Data1'
line 1
line 2
line 2
...
...
...
PAGE(enter) 'Data1'
我需要获取两个关键字之间的所有行并将其保存为文本文件。到目前为止,我遇到了以下情况。但我对single quotes 有疑问,因为 正则表达式 认为它是表达式中的引号而不是关键字。
到目前为止我的代码:
log_file = open('messages','r')
data = log_file.read()
block = re.compile(ur'PAGE\(leave\) \'Data1\'[\S ]+\s((?:(?![^\n]+PAGE\(enter\) \'Data1\').)*)', re.IGNORECASE | re.DOTALL)
data_in_home_block=re.findall(block, data)
file = 0
make_directory("home_to_home_data",1)
for line in data_in_home_block:
file = file + 1
with open("home_to_home_" + str(file) , "a") as data_in_home_to_home:
data_in_home_to_home.write(str(line))
如果有人能指导我如何实现它会很棒..
【问题讨论】:
-
所以你的文件实际上在括号前包含一个反斜杠?喜欢
\(? -
如果关键字不可变,为什么还要使用正则表达式?只需查找它们,在文本中获取它们的位置,然后检索它们之间的内容。
标签: python regex python-2.7 text-files