Open yagggi opened 6 years ago
# coding: utf-8 import re import sys def parse(xml_str, depth=0, pattern=None): if not pattern: pattern = re.compile('(<\/\w>|<\w>|<\w\/>)') res = pattern.search(xml_str) if not res: return start = res.start() end = res.end() tag = res.groups()[0] if start != 0: sys.stdout.write(' ' * 4 * depth + xml_str[:start] + '\n') sys.stdout.write(' ' * 4 * depth + tag + '\n') if '/' not in tag: depth += 1 else: depth -= 1 sub_str = xml_str[end:] parse(sub_str, depth=depth, pattern=pattern) if __name__ == '__main__': parse('<a>123<b>456<c/></b></a>')
囧, 首先把我觉得正则的pattern不太合适, 如果里面有数字咋整捏 然后把, 这个代码还是有问题的... 先回去改改吧
Question_ID: Q001
Language: Python2.7
Time Cost: 10-mins
Time Complexity: O(n)
Solution
My Code
Other