Files
ALL-teach_sys/frontend_化工/add_complete_interview_questions.py

206 lines
7.4 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import re
from datetime import datetime
def create_backup(file_path):
"""创建备份文件"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = f"{file_path}.backup_complete_{timestamp}"
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
with open(backup_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"已创建备份: {backup_path}")
return backup_path
def load_chemical_data():
"""加载化工岗位简历数据"""
with open('网页未导入数据/化工产业/化工岗位简历.json', 'r', encoding='utf-8') as f:
return json.load(f)
def parse_interview_questions(content):
"""解析面试题内容,提取问题和答案"""
questions = []
if not content:
return questions
# 提取模拟问答题
if "模拟问答题" in content:
# 分割问题部分
sim_section = content.split("# 二、")[0] if "# 二、" in content else content
# 查找每个问题
pattern = r'(\d+)\.\s*([^?]+[?])'
matches = re.findall(pattern, sim_section)
for i, (num, question) in enumerate(matches[:3]): # 取前3个
# 查找对应的示例答案
answer_pattern = rf'{num}\.[^示]*示例答案[:]\s*([^。;!?\n]+[。;!?])'
answer_match = re.search(answer_pattern, sim_section)
if answer_match:
answer = answer_match.group(1).strip()[:150] # 限制长度
else:
answer = "请参考专业培训资料获取详细解答。"
questions.append({
"id": f"q{i+1}",
"question": question.strip(),
"answer": answer
})
# 提取选择题
if "选择题" in content and len(questions) < 5:
choice_section = content.split("# 二、选择题")[1] if "# 二、选择题" in content else ""
if choice_section:
# 查找选择题
choice_pattern = r'(\d+)\.\s*([^?]+[^?\n]*[?])'
choice_matches = re.findall(choice_pattern, choice_section)
for i, (num, question) in enumerate(choice_matches[:2]): # 取前2个
# 查找答案
answer_pattern = rf'正确[答案选项][:]\s*([A-D,、\s]+)'
answer_match = re.search(answer_pattern, choice_section[choice_section.find(question):])
if answer_match:
answer = f"正确答案:{answer_match.group(1).strip()}"
else:
answer = "请查看答案解析"
questions.append({
"id": f"choice{i+1}",
"question": question.strip()[:100],
"answer": answer
})
# 如果没有找到题目,创建默认题目
if not questions:
questions = [
{
"id": "default1",
"question": "请介绍一下你对该岗位的理解和认识",
"answer": "需要掌握专业知识,注重安全生产,不断学习提升。"
},
{
"id": "default2",
"question": "你为什么选择化工行业",
"answer": "化工行业是国民经济的重要支柱,发展前景广阔。"
}
]
return questions
def update_interview_questions():
"""更新面试题数据"""
mock_file = 'src/mocks/resumeInterviewMock.js'
# 创建备份
backup_path = create_backup(mock_file)
# 加载化工数据
chemical_data = load_chemical_data()
# 按岗位群整理面试题
questions_by_group = {}
for item in chemical_data:
group = item.get('简历岗位群', '')
if group and group not in questions_by_group:
content = item.get('面试题内容', '')
questions = parse_interview_questions(content)
if questions:
questions_by_group[group] = questions
print(f"✓ 为 {group} 解析了 {len(questions)} 个面试题")
# 读取mock文件
with open(mock_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 逐行处理更新subQuestions
new_lines = []
i = 0
while i < len(lines):
line = lines[i]
new_lines.append(line)
# 查找 "subQuestions": []
if '"subQuestions": []' in line or '"subQuestions": [' in line:
# 查找对应的岗位群
group_name = None
for j in range(max(0, i-15), i):
if '"name":' in lines[j]:
match = re.search(r'"name":\s*"([^"]+)"', lines[j])
if match:
group_name = match.group(1)
break
if group_name and group_name in questions_by_group:
# 如果是空数组,替换为有内容的数组
if '[]' in line:
questions = questions_by_group[group_name]
# 生成格式化的JSON
questions_json = json.dumps(questions, ensure_ascii=False, indent=10)
lines_json = questions_json.split('\n')
# 替换当前行
new_lines[-1] = line.replace('[]', '[\n')
# 添加问题数据
for json_line in lines_json[1:-1]: # 跳过首尾的[]
new_lines.append(' ' + json_line + '\n')
new_lines.append(' ]\n')
print(f" 已更新 {group_name} 的面试题")
else:
# 如果已经有内容,跳过到结束
bracket_count = 1
i += 1
while i < len(lines) and bracket_count > 0:
if '[' in lines[i]:
bracket_count += lines[i].count('[')
if ']' in lines[i]:
bracket_count -= lines[i].count(']')
new_lines.append(lines[i])
if bracket_count == 0:
break
i += 1
i += 1
# 写回文件
with open(mock_file, 'w', encoding='utf-8') as f:
f.writelines(new_lines)
print("\n检查语法...")
# 验证语法
import subprocess
result = subprocess.run(['node', '-c', mock_file], capture_output=True, text=True)
if result.returncode == 0:
print("✓ 语法检查通过")
return True
else:
print("✗ 语法检查失败:")
print(result.stderr[:300])
# 恢复备份
with open(backup_path, 'r', encoding='utf-8') as f:
backup_content = f.read()
with open(mock_file, 'w', encoding='utf-8') as f:
f.write(backup_content)
print("已恢复备份文件")
return False
def main():
"""主函数"""
print("开始添加完整的面试题数据...\n")
if update_interview_questions():
print("\n✅ 面试题数据添加成功!")
else:
print("\n❌ 面试题数据添加失败")
if __name__ == "__main__":
main()