analyze_md_syntax.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import json
  2. import re
  3. jsonl_file = "prompt_jsonl/prompt_docs_refactored.jsonl"
  4. report = []
  5. def check_md_syntax(text, info_str):
  6. lines = text.split('\n')
  7. errors = []
  8. # 1. 检查分隔符 (--- 或 ***)
  9. # 规范:应独占一行,前后建议有空行
  10. # 正则匹配:行首开始,至少3个-或*,行尾结束,允许行尾有空白
  11. separator_pattern = re.compile(r'^\s*([-*]{3,})\s*$')
  12. # 2. 检查标题 (#)
  13. # 规范:#后必须有空格
  14. header_pattern = re.compile(r'^(#+)([^ \n].*)') # 捕获 #后紧跟非空格的
  15. # 3. 代码块 (```)
  16. code_block_count = 0
  17. for i, line in enumerate(lines):
  18. # 检查分隔符
  19. if separator_pattern.match(line):
  20. # 检查长度(虽然md规范>=3即可,但有些习惯是用3个)
  21. # 检查前后空行(非强制,但推荐)
  22. pass # 暂时只检查基本正则,如果夹杂在文本中通常不会独占一行
  23. # 检查错误标题: #Title
  24. m = header_pattern.match(line)
  25. if m:
  26. # 排除掉特殊的Shebang或注释,比如 #!/bin/bash 或 #_Role (这个文件里的Title字段用了#_)
  27. # 但这里是content字段,应该遵循MD规范
  28. # 检查是否在代码块内
  29. if code_block_count % 2 == 0:
  30. # 忽略一些特定的meta标记,比如 # Role (有些prompt习惯)
  31. # 实际上标准MD里 #Role 也是不规范的标题
  32. # 允许一些特殊情况? 暂时严格检查
  33. errors.append(f"Line {i+1}: 标题格式可能错误 (缺少空格): '{line[:20]}...'" )
  34. # 检查代码块闭合
  35. if line.strip().startswith('```'):
  36. code_block_count += 1
  37. if code_block_count % 2 != 0:
  38. errors.append("代码块 (```) 未闭合")
  39. if errors:
  40. report.append(f"\n📄 {info_str}")
  41. for e in errors:
  42. report.append(f" - {e}")
  43. def analyze():
  44. print("正在检查 Markdown 语法...")
  45. try:
  46. with open(jsonl_file, 'r', encoding='utf-8') as f:
  47. for line_num, line in enumerate(f, 1):
  48. if not line.strip(): continue
  49. try:
  50. item = json.loads(line)
  51. except json.JSONDecodeError:
  52. print(f"❌ JSON 解析错误在第 {line_num} 行")
  53. continue
  54. cat = item.get('category', 'Unknown')
  55. row = item.get('row', '?')
  56. title = item.get('title', 'No Title')
  57. content = item.get('content', '')
  58. if not content:
  59. report.append(f"\n⚠️ {cat} | Row {row} | {title}: 内容为空")
  60. continue
  61. info = f"[{cat}] Row {row}: {title}"
  62. check_md_syntax(content, info)
  63. except FileNotFoundError:
  64. print("文件未找到")
  65. return
  66. if not report:
  67. print("✅ 未发现明显的 Markdown 语法问题。 ")
  68. else:
  69. print(f"⚠️ 发现潜在问题 ({len(report)} 处):")
  70. for msg in report:
  71. print(msg)
  72. if __name__ == "__main__":
  73. analyze()