LLMValues / 4-HSLS /parse_recordfile.py
yijiexu's picture
Initial push, ignore notebooks
2a1ec59 verified
Raw History Blame Contribute Delete
5.22 kB
import json
import re
import os
def parse_codebook(codebook_file):
"""
解析 codebook.jsonl 文件。
Args:
codebook_file (str): codebook.jsonl 文件的路径。
Returns:
dict: 一个字典,键是变量名(name),值是对应的元数据。
"""
codebook_data = {}
with open(codebook_file, 'r', encoding='utf-8') as f:
for line in f:
try:
data = json.loads(line)
# 确保 'name' 键存在
if 'name' in data:
codebook_data[data['name']] = data
except json.JSONDecodeError:
print(f"警告: 无法解析行: {line}")
return codebook_data
def parse_variable_labels(layout_file,
start_marker="/* Variable Value Labels */"):
"""
解析包含变量值标签的文本文件。
Args:
layout_file (str): RecordFileLayout... .txt 文件的路径。
start_marker (str): 开始解析的标记。
Returns:
dict: 一个字典,键是变量名,值是响应选项的列表。
"""
value_labels = {}
current_variable = None
parsing_started = False
with open(layout_file, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
# 只有在找到起始标记后才开始解析
if not parsing_started:
if start_marker in line:
parsing_started = True
continue
# 去除行首行尾的空白字符
line = line.strip()
# 如果行为空,则跳过
if not line:
continue
# 如果行不是以数字或'-'开头,则假定它是一个新的变量名
if not (line[0].isdigit() or line.startswith('-')):
current_variable = line
if current_variable not in value_labels:
value_labels[current_variable] = []
# 否则,解析值和标签
elif current_variable:
# 使用正则表达式匹配 "code = 'text'" 格式
match = re.match(r'^(-?\d+\.?\d*)\s*=\s*"(.*)"', line)
if match:
code_str, text = match.groups()
# 将code转换为整数或浮点数
try:
code = int(code_str)
except ValueError:
code = float(code_str)
value_labels[current_variable].append({
"code": code,
"text": text
})
return value_labels
def main():
"""
主函数,执行整个数据处理流程。
"""
# --- 文件路径配置 ---
# 请确保这些文件与脚本在同一目录下,或者提供完整路径
codebook_filename = "codebook.jsonl"
layout_filename = "RecordFileLayout_HSLS_17_PETS_SR_STUDENT.txt"
output_filename = "record_file.jsonl"
# 检查所需文件是否存在
if not os.path.exists(codebook_filename):
print(f"错误: 文件 '{codebook_filename}' 未找到。请确保文件存在于当前目录。")
return
if not os.path.exists(layout_filename):
print(f"错误: 文件 '{layout_filename}' 未找到。请确保文件存在于当前目录。")
return
# 步骤 1: 解析 codebook
print(f"正在解析 '{codebook_filename}'...")
codebook = parse_codebook(codebook_filename)
print(f"成功解析 {len(codebook)} 个变量的元数据。")
# 步骤 2: 解析变量标签
print(f"正在解析 '{layout_filename}'...")
value_labels = parse_variable_labels(layout_filename)
print(f"成功解析 {len(value_labels)} 个变量的响应选项。")
# 步骤 3: 合并数据并生成输出
print("正在合并数据并生成输出文件...")
final_output = []
index_counter = 1
for var_name, var_info in codebook.items():
# question_text 使用 'label' 字段
question_text = var_info.get('label', 'N/A')
# response_options 来自解析的 value_labels
# 如果找不到,则留空列表
response_options = value_labels.get(var_name, [])
# 按照您期望的格式创建条目
# 注意: 'section' 和 'type' 字段在源文件中不可用,因此在此省略。
# 如果需要,可以手动添加或修改此处的逻辑。
# 'question_id' 使用变量名 `name`
output_item = {
"index": index_counter,
"question_id": var_name,
"question_text": question_text,
"description": var_info.get('description', ''),
"response_options": response_options
}
final_output.append(output_item)
index_counter += 1
# 步骤 4: 将结果写入输出文件
with open(output_filename, 'w', encoding='utf-8') as f:
for item in final_output:
f.write(json.dumps(item, ensure_ascii=False) + '\n')
print(f"\n处理完成!结果已保存到 '{output_filename}'。")
print(f"共生成 {len(final_output)} 条记录。")
if __name__ == "__main__":
main()