输入示例:如何在文件解压缩嵌套循环:Python的
Blank {Line0}
Loop 3 {Line1}
Blank {Line1a}
Label2: Blank {Line2}
Blank {Line3}
Loop 2 {Line4}
Blank {Line4a}
Label1: Blank {Line5} # I need to repeat the Jump statements as many times as mentioned in the Loop before the Label statement. Always The Loop statements precedes the immediate Jump statement. So here Line5, Lin6 and Line7 gets repeated twice. Jump to label1 so print line5, Line6 (since it has nothign going on) and Line7 is the end of Jump statement. Repeat it twice. Since Loop 2 {Line4} says do the following Jump Twice.
Blank {Line6}
Jump Label1 {Line7}
Blank {Line8}
Jump Label2 {Line9} # This jumps back to Label2. Which repeats everything until this line including the expanded inner loop ... This is the nested loop.
Blank {Line10}
输出例:
Line0
Line1
Line1a
Line2
Line3
Line4
Line4a
Line5
Line6
Line7
Line5
Line6
Line7
Line8
Line9
Line2
Line3
Line4
Line4a
Line5
Line6
Line7
Line5
Line6
Line7
Line8
Line9
Line2
Line3
Line4
Line4a
Line5
Line6
Line7
Line5
Line6
Line7
Line8
Line9
Line10
我现在有,对于在文件中循环和重复循环工作的代码。但打破上面给出的输入文件。我尝试从这里实现@Samy Arous方法:Using Python to Parse a File for Nested Loops但无法实现它。为了清晰起见,将其作为一个单独的问题提出。
所有的行只是字符串...这是一个有点复杂的格式,所以只是给了一个简单的。我们可以假设Blank,JUMP,LOOP都指导着需要完成的事情。无论是刚刚打印出来或重复基于循环和跳转
我的代码:
import sys
inputtfile = sys.stdin
inputfileContents = open(r'path to input file')
def extract(line):
return line[line.find('{') + 1: line.rfind('}')]
loopCount = 0
loopLines = []
inLoop = False
for line in inputfileContents:
if line.startswith('Loop '):
loopCount = int(line.split()[1])
inLoop = True
elif line.startswith('Jump '):
loopLines.append(extract(line))
for i in range(loopCount):
for loopLine in loopLines:
print loopLine
#reset state variables to track next possible loop
loopCount = 0
inLoop = False
loopLines = []
elif inLoop:
loopLines.append(extract(line))
else:
print extract(line)
这段代码甚至执行了吗?这些行: 'inLoop = True' 'loopLines.append(extract(line))'它们在'if'语句和'elif'之间,这是无效的 – smac89 2014-10-16 22:10:32
@ smac89。我纠正了它。应该在elif内...缩进错误.. – Doodle 2014-10-16 22:17:13
欢迎使用stackoverflow。如果您更多地了解您的问题而不是更多地了解您的解决方案,您将在这里获得更好的答案如果我不清楚你想要解决什么问题,我可能不会试着回答。一些提示,以改善您的问题:什么是所需的输出/行为? '{LineX}'事情真的是你的输入文件的一部分? – 2014-10-16 22:48:00