我正在尝试使用Python编写一个程序,当遇到某些字符(例如花括号)时,它将自动缩进字符串的下一行。
例如:
public class Example{
--indent--> public static void main (String[]args){
--indent--> System.out.println("Hello");
}
}
我似乎无法掌握实现该目标所需的编码。
任何帮助将不胜感激!
这是一种快速而肮脏的方法。基本上,我只是遍历输入字符串(cppcode
)的行并跟踪当前的缩进(tabdepth
)。当我在输入行中遇到支撑时,我向上或向下增加制表符深度,然后将tabdepth
个制表符添加到输出行。
cppcode = '''
public class Example{
public static void main (String[]args){
System.out.println("Hello");
}
}
'''
tabdepth = 0
for line in cppcode.split("\n"):
depth_changed = False
indentedline = ''.join(['\t'*tabdepth, line])
for c in line:
if c == '{':
tabdepth += 1
elif c == '}':
tabdepth -= 1
depth_changed = True
if depth_changed:
indentedline = ''.join(['\t'*tabdepth, line])
print(indentedline)
老实说,设置代码的确切方式取决于您是否正在对代码进行“漂亮打印”。大概的轮廓看起来像这样
def pretty(s):
start = "{"
end = "}"
level = 0
skip_start = False
for c in s:
# raise or lower indent level
if c == start:
level += 1
if c == end:
level -= 1
if level < 0:
raise IndentationError("Error Indenting")
if c == "\n":
skip_start = True # I'm bad at naming just a flag to mark new lines
if c.isspace() and skip_start:
pass #skip whitspace at start of line
else:
if skip_start:
print("\n", " " * level, end="") #print indent level
skip_start = False
print(c, end = "") #print character
pretty('''
public class Example{
public static void main (String[]args){
if (1==1){
//do thing
//do other thing
// weird messed up whitespace
}else{
System.out.println("Hello");
}
}
}
''')
将输出
public class Example{
public static void main (String[]args){
if (1==1){
//do thing
//do other thing
// weird messed up whitespace
}else{
System.out.println("Hello");
}
}
}