Files
ALL-teach_sys/frontend_智能制造/update_interview_questions_fixed.py

192 lines
6.8 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import re
from datetime import datetime
# 读取智能制造岗位简历数据
print("正在读取智能制造岗位简历.json...")
with open('网页未导入数据/智能制造产业/智能制造岗位简历.json', 'r', encoding='utf-8') as f:
smart_mfg_data = json.load(f)
# 读取当前mock文件
print("正在读取当前mock文件...")
with open('src/mocks/resumeInterviewMock.js', 'r', encoding='utf-8') as f:
mock_content = f.read()
# 备份原文件
backup_time = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_file = f'src/mocks/resumeInterviewMock.js.backup_complete_{backup_time}'
with open(backup_file, 'w', encoding='utf-8') as f:
f.write(mock_content)
print(f"已创建备份文件: {backup_file}")
# 解析智能制造岗位简历数据,构建完整的面试题映射
interview_data_map = {}
for item in smart_mfg_data:
job_group = item.get('简历岗位群', '')
interview_content = item.get('面试题内容', '')
if job_group and interview_content:
# 解析面试题内容
questions_data = []
lines = interview_content.split('\n')
current_section = None
current_section_questions = []
section_id = 1
i = 0
while i < len(lines):
line = lines[i].strip()
if not line:
i += 1
continue
# 大标题(如 # 一、xxx
if line.startswith('# '):
# 保存上一个section
if current_section and current_section_questions:
questions_data.append({
'id': f'group_q{section_id}',
'title': current_section,
'questions': current_section_questions
})
section_id += 1
current_section = line[2:].strip()
current_section_questions = []
# 问题编号(如 1. xxx 或 1、xxx
elif re.match(r'^(\d+)[\.、]\s+', line):
# 提取问题
question_match = re.match(r'^(\d+)[\.、]\s+(.+)', line)
if question_match:
question_text = question_match.group(2).strip()
# 查找答案
answer_lines = []
i += 1 # 移动到下一行
# 继续读取直到找到答案或下一个问题
while i < len(lines):
next_line = lines[i].strip()
# 如果遇到下一个问题或章节,停止
if next_line.startswith('#') or re.match(r'^(\d+)[\.、]\s+', next_line):
i -= 1 # 回退一行,让外层循环处理
break
# 如果是答案标记
if re.match(r'^(示例答案|答案)[:]?\s*', next_line):
# 提取答案内容
answer_text = re.sub(r'^(示例答案|答案)[:]?\s*', '', next_line)
if answer_text:
answer_lines.append(answer_text)
elif next_line:
# 其他非空行也作为答案的一部分
answer_lines.append(next_line)
i += 1
answer = ' '.join(answer_lines).strip()
if not answer:
answer = "请根据实际情况回答"
current_section_questions.append({
'question': question_text,
'answer': answer
})
continue
i += 1
# 保存最后一个section
if current_section and current_section_questions:
questions_data.append({
'id': f'group_q{section_id}',
'title': current_section,
'questions': current_section_questions
})
interview_data_map[job_group] = questions_data
print(f"\n共解析 {len(interview_data_map)} 个岗位群的面试题数据")
# 统计解析结果
for group, data in interview_data_map.items():
total_questions = sum(len(section['questions']) for section in data)
print(f" - {group}: {len(data)} 个章节,{total_questions} 道题")
# 更新mock文件中的面试题
def update_industry_questions(match):
full_match = match.group(0)
industry_name = match.group(1)
# 查找对应的面试题数据
if industry_name not in interview_data_map:
print(f" - {industry_name}: 保持原样(未找到对应数据)")
return full_match
questions_data = interview_data_map[industry_name]
# 构建新的questions数组
new_questions = []
for section_data in questions_data:
sub_questions = []
for idx, q in enumerate(section_data['questions']):
# 转义特殊字符
question_text = q['question'].replace('\\', '\\\\').replace('"', '\\"')
answer_text = q['answer'].replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
sub_questions.append(f'''{{
"id": "q{section_data['id'][7:]}_{idx+1}",
"question": "{question_text}",
"answer": "{answer_text}"
}}''')
section_title = section_data['title'].replace('\\', '\\\\').replace('"', '\\"')
new_questions.append(f'''{{
"id": "{section_data['id']}",
"question": "# {section_title}",
"subQuestions": [
{','.join(sub_questions)}
]
}}''')
# 替换questions部分
questions_str = ',\n '.join(new_questions)
# 构建完整的替换内容
before_questions = match.group(0).split('"questions": [')[0]
result = before_questions + '"questions": [\n ' + questions_str + '\n ]'
# 统计题目数量
total_questions = sum(len(section['questions']) for section in questions_data)
print(f" - {industry_name}: 更新为 {len(questions_data)} 个章节,{total_questions} 道题")
return result
# 执行更新
print("\n正在更新面试题数据...")
pattern = r'"name":\s*"([^"]+)"[^}]*?"questions":\s*\[.*?\]\s*(?=\})'
new_content = re.sub(pattern, update_industry_questions, mock_content, flags=re.DOTALL)
# 保存更新后的文件
with open('src/mocks/resumeInterviewMock.js', 'w', encoding='utf-8') as f:
f.write(new_content)
print("\n✅ 面试题数据更新完成!")
# 验证语法
import subprocess
result = subprocess.run(['node', '-c', 'src/mocks/resumeInterviewMock.js'],
capture_output=True, text=True)
if result.returncode == 0:
print("✅ 语法检查通过!")
else:
print("❌ 语法错误:")
print(result.stderr)