下面是工作只是粗略地拼湊
def format(text):
depth = 0
result = ''
text = text.replace(' ', '')
for i in range(len(text)):
c = text[i]
if c == '(':
depth += 1
result += '\n' + ' ' * depth + '('
elif c == ')':
depth -= 1
if text[i-1] != ')':
result += ')'
else:
result += '\n' + ' ' * depth + ')'
else:
result += c
return result.strip()
s = "(Root (AB (ABC) (CBA)) (CD (CDE) (FGH)))"
print(format(s))
<script src="//repl.it/embed/IS2q/5.js"></script>
你應該明白爲什麼人們並不熱衷於回答這個問題的解決方案。您正在進入解析部門,但忽略了它的複雜性。要實現你的目標正確你需要一個原始格式的定義語法,那麼你需要根據該語法進行解析。所得到的內部結構,即解析樹/語法樹,然後需要被格式化爲所需的形式。
我的建議是使用完善的標準,如json來代表您的數據,而不是自定義的,即原始文本。