# update: 2024.9.4 """ cd /media/nvidia/nvme0n1/server/repositories/repositories/sri-project.demo-py/3rdparty/xlib python3 xmarkdwon.py """ def read_text(file_path): with open(file_path, 'r') as f: return f.read() if __name__ == '__main__': file_path = '/media/nvidia/nvme0n1/server/repositories/repositories/sri-project.demo-py/sri-agent-tool01/factories/README-test.md' # --- 获取唯一的表格数据, text = read_text(file_path) t_list = text.split('|')[1:-1] table_text = '|' + '|'.join(t_list) + '|' print(table_text) # | 名称 | 年龄 | 职业 | # |----------|------|----------| # | 张三 | 28 | 软件工程师 | # | 李四 | 35 | 数据科学家 | # | 王五 | 22 | 产品经理 | # --- 字符转字典 # 分割表格行 lines = table_text.strip().split("\n") # 获取表头 headers = [header.strip() for header in lines[0].split("|") if header] # 解析数据行 data = [] for line in lines[2:]: # 跳过表头分隔线 values = [value.strip() for value in line.split("|") if value] row = dict(zip(headers, values)) data.append(row) print(data) # --- 字典转字符 # 获取表头 headers = data[0].keys() # 创建表头行 header_row = "| " + " | ".join(headers) + " |" # 创建分隔行 separator_row = "| " + " | ".join(["-" * len(header) for header in headers]) + " |" # 创建数据行 data_rows = [] for item in data: row = "| " + " | ".join(item.values()) + " |" data_rows.append(row) # 合并所有行 markdown_table = "\n".join([header_row, separator_row] + data_rows) print(markdown_table)