导出为 CSV 格式
(records: List[Dict], output_path: Path, flatten_func=None)
| 154 | |
| 155 | |
| 156 | def export_to_csv(records: List[Dict], output_path: Path, flatten_func=None) -> None: |
| 157 | """导出为 CSV 格式""" |
| 158 | if not records: |
| 159 | print(" No records to export") |
| 160 | return |
| 161 | |
| 162 | # 扁平化 |
| 163 | if flatten_func: |
| 164 | records = [flatten_func(r) for r in records] |
| 165 | |
| 166 | # 获取所有字段 |
| 167 | all_fields = set() |
| 168 | for r in records: |
| 169 | all_fields.update(r.keys()) |
| 170 | |
| 171 | # 排序字段(日期和用户 ID 在前) |
| 172 | priority_fields = ["date", "timestamp", "user_id", "episode_id", "role_name"] |
| 173 | fields = [f for f in priority_fields if f in all_fields] |
| 174 | fields.extend(sorted(all_fields - set(fields))) |
| 175 | |
| 176 | with output_path.open("w", encoding="utf-8-sig", newline="") as f: |
| 177 | writer = csv.DictWriter(f, fieldnames=fields) |
| 178 | writer.writeheader() |
| 179 | writer.writerows(records) |
| 180 | |
| 181 | print(f" Exported {len(records)} records to {output_path}") |
| 182 | |
| 183 | |
| 184 | def export_to_jsonl(records: List[Dict], output_path: Path, flatten_func=None) -> None: |
nothing calls this directly
no outgoing calls
no test coverage detected