extract_bid_toc.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. Phase 1: 招标文件解析 — 从历史投标文件提取目录结构
  3. 用法:
  4. from phase1_parsing.extract_bid_toc import extract_toc
  5. toc = extract_toc("投标文件_extracted.txt")
  6. """
  7. import os
  8. def extract_toc(text: str) -> list:
  9. """
  10. 从历史投标文件的文本中提取目录结构。
  11. 目录行通常包含 "..." + 页码,按缩进判断层级。
  12. Args:
  13. text: 历史投标文件的文本内容
  14. Returns:
  15. [{"title": "章节名", "level": 1-3, "page": "页码"}, ...]
  16. """
  17. lines = text.split("\n")
  18. toc_lines = []
  19. toc_started = False
  20. toc_start_keywords = ["目 录", "目录", "商务部分"]
  21. for i, line in enumerate(lines[:300]):
  22. line_stripped = line.strip()
  23. if not line_stripped:
  24. continue
  25. if any(kw in line_stripped for kw in toc_start_keywords):
  26. toc_started = True
  27. continue
  28. if not toc_started:
  29. continue
  30. if line_stripped.startswith("第一章") and len(toc_lines) > 3:
  31. break
  32. if "..." in line_stripped and any(c.isdigit() for c in line_stripped):
  33. title = line_stripped.split("...")[0].strip()
  34. indent = len(line) - len(line.lstrip(" "))
  35. level = 3 if indent > 5 else (2 if indent > 2 else 1)
  36. page_num = ""
  37. parts = line_stripped.split("...")
  38. if parts:
  39. last_part = parts[-1].strip()
  40. if last_part.isdigit():
  41. page_num = last_part
  42. toc_lines.append({
  43. "title": title,
  44. "level": level,
  45. "page": page_num,
  46. })
  47. return toc_lines
  48. if __name__ == "__main__":
  49. import sys
  50. sys.stdout.reconfigure(encoding="utf-8")
  51. with open("松江区机关事务管理局物业管理服务项目投标文件_extracted.txt",
  52. "r", encoding="utf-8") as f:
  53. text = f.read()
  54. toc = extract_toc(text)
  55. print(f"提取到 {len(toc)} 行目录")
  56. for item in toc[:30]:
  57. indent = " " * (item["level"] - 1)
  58. print(f" {indent}{item['title']} (p.{item['page']})")