我试图从包含以下数据的文本文件中获取两个字符串之间的数据:
X_0_Gui_Homescreen_FPS_List
commands 1 :SensorFps ( 30.000)
X_0_Gui_Homescreen_Homescreen
X_0_Gui_Homescreen_EI_Switchview
X_0_Gui_Homescreen_EI_Set
commands 2 :SetExIndex (12), SetExIndex (13), EiSwitchAssign (1, 13)
X_0_Gui_Homescreen_EI_Switchview
X_0_Gui_Homescreen_Homescreen
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_100_Menu_Recording
commands 3 :MediaCodec (4), SetSensorFormat (0)
X_0_Gui_Menu_110_Menu_Recording_Project
commands 4 :ProjectFps (0), SensorFps ( 23.976)
X_0_Gui_Menu_100_Menu_Recording
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_300_Menu_Outputs
X_0_Gui_Menu_310_Menu_Outputs_EVF_mon
commands 5 :ZoomPos (0)
X_0_Gui_Menu_312_Menu_Outputs_EVF_exptools
commands 6 :ExposureToolSel (0, 1), ExposureToolSel (1, 1), ZebraMode (0, 0), ZebraMode (1, 0)
X_0_Gui_Menu_310_Menu_Outputs_EVF_mon
X_0_Gui_Menu_317_Menu_Outputs_EVF_settings
X_0_Gui_Menu_310_Menu_Outputs_EVF_mon
X_0_Gui_Menu_311_Menu_Outputs_EVF_overlays
commands 7 :CenterMark (0, 1)
我希望获得如下输出:
Navigated pages 1:
X_0_Gui_Homescreen_FPS_List
Navigated pages 2:
X_0_Gui_Homescreen_Homescreen
X_0_Gui_Homescreen_EI_Switchview
X_0_Gui_Homescreen_EI_Set
Navigated pages 3:
X_0_Gui_Homescreen_EI_Switchview
X_0_Gui_Homescreen_Homescreen
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_100_Menu_Recording
依旧......(命令1之前的数据应进入Navigated pages 1
,命令2和1之间的数据应进入Navigated pages 2
等等)
到目前为止完成的代码:
def get_navigated_path(command_number):
navigated_and_commands = open('navigated_and_commands','r')
data = navigated_and_commands.read()
block = ""
for i in range(0,command_number):
block = re.compile(ur'commands ' + str(i) + ' :' + '[\S ]+\s((?:(?![^\n]+commands ' + str(i+1) + ' :' + ').)*)', re.IGNORECASE | re.DOTALL)
data_with_block=re.findall(block, data)
for line in data_with_block:
if "X_" in line:
print " > navigated pages: \n" + " " + line
使用
产生几乎所需的输出 > navigated pages:
X_0_Gui_Homescreen_Homescreen
X_0_Gui_Homescreen_EI_Switchview
X_0_Gui_Homescreen_EI_Set
commands 2 :SetExIndex (12), SetExIndex (13), EiSwitchAssign (1, 13)
我不需要行commands 2 :SetExIndex (12), SetExIndex (13), EiSwitchAssign (1, 13)
而且我希望它像这样组织
> navigated pages:
X_0_Gui_Homescreen_Homescreen
X_0_Gui_Homescreen_EI_Switchview
X_0_Gui_Homescreen_EI_Set
任何指导都会非常感激
答案 0 :(得分:1)
我不会使用正则表达式...可能是一个简单的迭代可以适合这种情况:
def get_navigated_path(command_number):
navigated_and_commands = open('navigated_and_commands','r')
i = 0
for line in navigated_and_commands.readlines():
if line.startswith("commands %d"%command_number):
break
if line.startswith("commands"):
i += 1
print "Navigated pages %d"%i
continue
print line