flatten.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. # 把规格书的组件化 Markdown(<Heading>/<Paragraph>/<Table>…)转成紧凑纯文本,便于阅读
  2. import re
  3. import sys
  4. src = sys.argv[1]
  5. dst = sys.argv[2]
  6. text = open(src, encoding='utf-8').read()
  7. # Mark bold/italic 保留语义
  8. text = re.sub(r'<Mark bold>(.*?)</Mark>', r'**\1**', text, flags=re.S)
  9. text = re.sub(r'<Mark italic>(.*?)</Mark>', r'_\1_', text, flags=re.S)
  10. text = re.sub(r'<Mark[^>]*>(.*?)</Mark>', r'\1', text, flags=re.S)
  11. # 代码块
  12. text = re.sub(r'<CodeBlock[^>]*>(.*?)</CodeBlock>', r'\n```\n\1\n```\n', text, flags=re.S)
  13. # 结构标记 → 文本标记
  14. text = re.sub(r'<Heading[^>]*level="(\d)"[^>]*>', lambda m: '\n' + '#' * int(m.group(1)) + ' ', text)
  15. text = re.sub(r'<Divider[^>]*/?>', '\n---\n', text)
  16. text = re.sub(r'<NumberedList[^>]*>', '\n- ', text)
  17. text = re.sub(r'<BulletList[^>]*>', '\n- ', text)
  18. text = re.sub(r'<TableRow[^>]*>', '\n| ', text)
  19. text = re.sub(r'<TableCell[^>]*>', ' ', text)
  20. text = re.sub(r'<Table[^>]*>', '\n', text)
  21. text = re.sub(r'<Paragraph[^>]*>', '\n', text)
  22. text = re.sub(r'<BlockQuote[^>]*>', '\n> ', text)
  23. text = re.sub(r'<Callout[^>]*>', '\n[!] ', text)
  24. # 其余块级标签换行,行内/闭合标签直接删
  25. text = re.sub(r'</(Heading|NumberedList|BulletList|TableRow|Table|Paragraph|BlockQuote|Callout)>', '\n', text)
  26. text = re.sub(r'<[^>]+>', '', text)
  27. text = text.replace('\\<', '<').replace('\\>', '>')
  28. text = re.sub(r'\n{3,}', '\n\n', text)
  29. open(dst, 'w', encoding='utf-8').write(text)
  30. print('lines=%d chars=%d' % (text.count('\n') + 1, len(text)))