xmarkdwon.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # update: 2024.9.4
  2. """
  3. cd /media/nvidia/nvme0n1/server/repositories/repositories/sri-project.demo-py/3rdparty/xlib
  4. python3 xmarkdwon.py
  5. """
  6. def read_text(file_path):
  7. with open(file_path, 'r') as f:
  8. return f.read()
  9. if __name__ == '__main__':
  10. file_path = '/media/nvidia/nvme0n1/server/repositories/repositories/sri-project.demo-py/sri-agent-tool01/factories/README-test.md'
  11. # --- 获取唯一的表格数据,
  12. text = read_text(file_path)
  13. t_list = text.split('|')[1:-1]
  14. table_text = '|' + '|'.join(t_list) + '|'
  15. print(table_text)
  16. # | 名称 | 年龄 | 职业 |
  17. # |----------|------|----------|
  18. # | 张三 | 28 | 软件工程师 |
  19. # | 李四 | 35 | 数据科学家 |
  20. # | 王五 | 22 | 产品经理 |
  21. # --- 字符转字典
  22. # 分割表格行
  23. lines = table_text.strip().split("\n")
  24. # 获取表头
  25. headers = [header.strip() for header in lines[0].split("|") if header]
  26. # 解析数据行
  27. data = []
  28. for line in lines[2:]: # 跳过表头分隔线
  29. values = [value.strip() for value in line.split("|") if value]
  30. row = dict(zip(headers, values))
  31. data.append(row)
  32. print(data)
  33. # --- 字典转字符
  34. # 获取表头
  35. headers = data[0].keys()
  36. # 创建表头行
  37. header_row = "| " + " | ".join(headers) + " |"
  38. # 创建分隔行
  39. separator_row = "| " + " | ".join(["-" * len(header) for header in headers]) + " |"
  40. # 创建数据行
  41. data_rows = []
  42. for item in data:
  43. row = "| " + " | ".join(item.values()) + " |"
  44. data_rows.append(row)
  45. # 合并所有行
  46. markdown_table = "\n".join([header_row, separator_row] + data_rows)
  47. print(markdown_table)