import re import json import sys from tqdm import tqdm def parse_codebook_to_jsonl(input_text_file, output_jsonl_file): """ 将一个特定格式的 codebook 文本文件解析并转换为 JSONL 文件。 此版本经过修正,能够将所有非结构化字段(如 Description, Please note, SAS Logic 等)的内容统一合并到 'description' 键下,以满足特定需求。 Args: input_text_file (str): 输入的 codebook 文本文件路径。 output_jsonl_file (str): 输出的 JSONL 文件路径。 """ try: with open(input_text_file, 'r', encoding='utf-8') as f: content = f.read() except FileNotFoundError: print(f"❌ 错误:输入文件 '{input_text_file}' 未找到。请确保文件存在且路径正确。") sys.exit(1) except Exception as e: print(f"❌ 读取文件时发生错误: {e}") sys.exit(1) # 1. 分割记录 # 使用正则表达式按双虚线分隔符来分割整个文件内容。 blocks = re.split(r'\n-+\n-+\s*\n', content) # 初始化统计计数器和失败记录列表 success_count = 0 failure_count = 0 failed_records = [] # 定义标准、结构化的字段键名 STANDARD_KEYS = {'file', 'name', 'position', 'length', 'label'} print(f"🚀 开始解析文件 '{input_text_file}'...") with open(output_jsonl_file, 'w', encoding='utf-8') as outfile: # 定义用于匹配 "Key: Value" 格式的正则表达式 key_pattern = re.compile(r'^([\w\s/()-]+?):\s*(.*)$') for block in tqdm(blocks, desc="解析变量记录", unit="条"): block = block.strip() # 跳过文件头、结尾或空的文本块 if not block or not block.startswith("File:"): continue try: # --- 步骤 1: 初步解析为临时字典 --- temp_record = {} current_key = None value_buffer = [] lines = block.split('\n') for line in lines: match = key_pattern.match(line) if match: if current_key: temp_record[current_key] = '\n'.join( value_buffer).strip() key = match.group(1).strip().lower().replace(' ', '_') value = match.group(2).strip() current_key = key value_buffer = [value] if value else [] elif current_key: value_buffer.append(line) if current_key: temp_record[current_key] = '\n'.join(value_buffer).strip() if not temp_record: continue # --- 步骤 2: 后处理,将非标准字段合并到 description --- final_record = {} description_parts = [] # 遍历临时记录的键,为了保持原始顺序,可以对键进行排序(可选,但推荐) # 这里我们假设原始顺序不重要,或者temp_record(Python 3.7+)保持插入顺序 for key, value in temp_record.items(): if key in STANDARD_KEYS: # 如果是标准键,直接复制 final_record[key] = value else: # 如果是非标准键,将其值存入 description 列表 # 为了保持内容干净,我们只合并值,不添加原始键名 description_parts.append(value) # 合并所有描述性内容 if description_parts: final_record['description'] = '\n\n'.join( description_parts).strip() # 转换数值类型 for field in ['position', 'length']: if field in final_record: try: final_record[field] = int(final_record[field]) except (ValueError, TypeError): # 保留原始值并在需要时添加错误标记 pass # 写入文件 json.dump(final_record, outfile, ensure_ascii=False) outfile.write('\n') success_count += 1 except Exception as e: failure_count += 1 failed_records.append({ "error": str(e), "block_content": block }) # 3. 打印最终的统计报告 print("\n" + "=" * 50) print("🎉 解析完成!") print("=" * 50) print(f"📊 统计报告:") print(f" - 总共处理记录块: {len(blocks)}") print(f" - ✅ 成功解析并写入: {success_count} 条") print(f" - ❌ 解析失败: {failure_count} 条") print("=" * 50) if failure_count > 0: print("\n🔍 以下是解析失败的记录详情:\n") for i, failure in enumerate(failed_records, 1): print(f"--- 失败记录 {i} ---") print(f"错误原因: {failure['error']}") print("原始文本块:") print("-" * 20) print(failure['block_content']) print("-" * 20 + "\n") print(f"✨ 结果已保存至 '{output_jsonl_file}'。") # --- 如何使用 --- # 1. 将此脚本保存为 .py 文件(例如 parser.py)。 # 2. 确保你的数据文件 'Codebook_HSLS_17_PETS.txt' 与脚本在同一目录。 # 3. 运行脚本: python parser.py if __name__ == "__main__": # 定义输入和输出文件名 input_file = 'Codebook_HSLS_17_PETS.txt' output_file = 'codebook.jsonl' # 调用主函数 parse_codebook_to_jsonl(input_file, output_file)