Files
ALL-teach_sys/frontend_视觉设计/safe_update_interview_questions.py

205 lines
8.2 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import re
from datetime import datetime
def load_visual_design_data():
"""加载视觉设计岗位简历数据"""
with open('网页未导入数据/视觉设计产业/视觉设计岗位简历.json', 'r', encoding='utf-8') as f:
return json.load(f)
def extract_questions_from_content(content, industry_name):
"""从面试题内容中提取问题和答案"""
questions = []
# 提取所有问题(保持原始格式)
pattern = r'(\d+)\.\s*问题[:]?\s*(.*?)(?:\n\s*)?(?:参考回答[:]?)(.*?)(?=\d+\.\s*问题|$)'
matches = re.findall(pattern, content, re.DOTALL)
# 如果有subQuestions结构需要创建分组
if len(matches) > 0:
# 创建主问题组
sub_questions = []
for i, match in enumerate(matches[:10], 1): # 限制为前10个问题
q_num = match[0]
question_text = match[1].strip()
answer_text = match[2].strip()
sub_questions.append({
"id": f"q{i}_{q_num}",
"question": question_text,
"answer": answer_text
})
# 返回带有subQuestions的结构
questions.append({
"id": "group_q1",
"question": f"# {industry_name}面试题",
"subQuestions": sub_questions
})
return questions
def create_backup():
"""创建备份文件"""
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
backup_name = f'src/mocks/resumeInterviewMock.js.backup_{timestamp}_safe'
with open('src/mocks/resumeInterviewMock.js', 'r', encoding='utf-8') as f:
content = f.read()
with open(backup_name, 'w', encoding='utf-8') as f:
f.write(content)
print(f"✓ 已创建备份: {backup_name}")
return backup_name
def update_mock_file():
"""安全更新mock文件中的面试题数据"""
# 创建备份
backup_file = create_backup()
try:
# 加载视觉设计数据
visual_data = load_visual_design_data()
# 读取现有mock文件
with open('src/mocks/resumeInterviewMock.js', 'r', encoding='utf-8') as f:
mock_content = f.read()
# 创建岗位群到岗位名称的映射
industry_map = {
"UI设计": ["UI设计师"],
"包装设计": ["包装设计师", "包装设计师助理"],
"插画设计": ["插画师"],
"摄影/摄像": ["摄影师", "影视摄像", "摄影摄像助理"],
"灯光": ["影视灯光", "摄影美术指导助理", "灯光助理"],
"动画设计": ["动画师"],
"平面设计": ["平面设计师"],
"品牌设计": ["品牌视觉内容策划", "品牌视觉传播策划管培生"],
"三维设计": ["CG总监助理", "3D建模师", "3D特效师"],
"后期特效": ["特效设计师", "特效合成师", "渲染合成师"],
"剪辑": ["剪辑师", "剪辑助理", "影视剪辑", "短视频剪辑师"],
"调色": ["调色师"],
"音频处理": ["录音师", "音效设计师", "音频编辑师", "混音师"],
"直播": ["直播专员", "直播助理", "直播运营"],
"新媒体运营": ["新媒体运营专员", "自媒体运营专员", "内容运营", "用户运营", "社群运营"],
"影视节目策划": ["文案策划", "导演"],
"室内设计": ["室内设计师"]
}
updated_count = 0
errors = []
# 为每个岗位群更新面试题
for industry_name, position_names in industry_map.items():
try:
# 查找该岗位群的第一个岗位的面试题
questions = []
used_position = None
for position_name in position_names:
for item in visual_data:
if item.get('岗位名称') == position_name and item.get('面试题内容'):
questions = extract_questions_from_content(
item.get('面试题内容', ''),
industry_name
)
used_position = position_name
break
if questions:
break
if not questions:
print(f"⚠️ 未找到面试题:{industry_name}")
continue
# 构建新的questions数组内容
questions_json = json.dumps(questions, ensure_ascii=False, indent=2)
# 调整缩进
questions_json = '\n'.join([' ' + line if line.strip() else line
for line in questions_json.split('\n')])
# 查找并替换该岗位群的questions
# 使用更精确的模式匹配
pattern = rf'("name":\s*"{re.escape(industry_name)}"[^{{]*?"questions":\s*)\[[^\]]*?\]'
def replace_func(match):
prefix = match.group(1)
return prefix + questions_json.strip()
# 执行替换
new_content = re.sub(pattern, replace_func, mock_content, count=1, flags=re.DOTALL)
if new_content != mock_content:
mock_content = new_content
updated_count += 1
print(f"✓ 已更新岗位群:{industry_name} (使用岗位:{used_position})")
else:
print(f"✗ 未能更新岗位群:{industry_name}")
except Exception as e:
errors.append(f"{industry_name}: {str(e)}")
print(f"✗ 更新{industry_name}时出错: {str(e)}")
# 验证JSON语法
try:
# 尝试解析生成的内容移除JS部分
test_content = mock_content.replace('const industries = ', '').replace('const resumes = ', '').replace('export { industries, resumes };', '').replace('export function getMockPageData() {', '').replace('return {', '{').replace('};', '}').replace('};\n}', '}')
# 这只是基本检查
print("\n正在验证语法...")
except Exception as e:
print(f"⚠️ 语法验证警告: {str(e)}")
# 写回文件
with open('src/mocks/resumeInterviewMock.js', 'w', encoding='utf-8') as f:
f.write(mock_content)
print(f"\n✅ Mock文件更新完成")
print(f" 成功更新: {updated_count}个岗位群")
if errors:
print(f" 出错: {len(errors)}")
for error in errors:
print(f" - {error}")
# 验证文件语法
import subprocess
try:
result = subprocess.run(['node', '-c', 'src/mocks/resumeInterviewMock.js'],
capture_output=True, text=True)
if result.returncode == 0:
print("✅ 文件语法验证通过")
else:
print(f"⚠️ 文件语法验证失败: {result.stderr}")
print(f"恢复备份文件: {backup_file}")
# 恢复备份
with open(backup_file, 'r', encoding='utf-8') as f:
backup_content = f.read()
with open('src/mocks/resumeInterviewMock.js', 'w', encoding='utf-8') as f:
f.write(backup_content)
print("已恢复到备份版本")
except Exception as e:
print(f"⚠️ 无法验证文件语法: {str(e)}")
except Exception as e:
print(f"✗ 更新过程出错: {str(e)}")
print(f"备份文件位置: {backup_file}")
# 恢复备份
try:
with open(backup_file, 'r', encoding='utf-8') as f:
backup_content = f.read()
with open('src/mocks/resumeInterviewMock.js', 'w', encoding='utf-8') as f:
f.write(backup_content)
print("已恢复到备份版本")
except:
print("无法自动恢复,请手动恢复备份")
if __name__ == '__main__':
print("=== 安全更新面试题数据 ===\n")
update_mock_file()
print("\n请刷新页面查看效果")