Files
ALL-teach_sys/frontend_视觉设计/robustReplaceQuestions.cjs

228 lines
6.6 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
const fs = require('fs');
// Load visual design data
const visualDesignData = JSON.parse(
fs.readFileSync('网页未导入数据/视觉设计产业/视觉设计岗位简历.json', 'utf-8')
);
// Create backup
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
const backupPath = `src/mocks/resumeInterviewMock.js.backup_${timestamp}_robust`;
const mockContent = fs.readFileSync('src/mocks/resumeInterviewMock.js', 'utf-8');
fs.writeFileSync(backupPath, mockContent);
console.log(`✓ Backup created: ${backupPath}`);
// Position mapping
const industryPositionMap = {
'UI设计': 'UI设计师',
'包装设计': '包装设计师',
'插画设计': '插画师',
'灯光': '影视灯光',
'动画设计': '动画师',
'后期特效': '特效设计师',
'剪辑': '剪辑师',
'品牌设计': '品牌视觉内容策划',
'平面设计': '平面设计师',
'三维设计': 'CG总监助理',
'摄影/摄像': '摄影师',
'室内设计': '室内设计师',
'调色': '调色师',
'新媒体运营': '新媒体运营专员',
'音频处理': '录音师',
'影视节目策划': '文案策划',
'直播': '直播专员'
};
// Extract questions from content
function extractQuestions(content, industryName) {
const questions = [];
// Updated regex to handle various formats in the source data
const patterns = [
/(\d+)\.\s*[:]?\s*(.*?)(?:\n\s*)?[:]?\s*(.*?)(?=\d+\.\s*|$)/gs,
/(\d+)[\.]\s*[:]?\s*(.*?)\n\s*[:]?\s*(.*?)(?=\d+[\.]\s*|$)/gs,
/(\d+)[:]?\s*(.*?)\n\s*[:]?\s*(.*?)(?=\d+|$)/gs
];
let matches = [];
for (const pattern of patterns) {
const tempMatches = [...content.matchAll(pattern)];
if (tempMatches.length > 0) {
matches = tempMatches;
break;
}
}
// Take up to 5 questions
for (let i = 0; i < Math.min(5, matches.length); i++) {
const match = matches[i];
const questionText = match[2].trim();
const answerText = match[3].trim();
questions.push({
id: `q1_${i + 1}`,
question: questionText,
answer: answerText
});
}
if (questions.length > 0) {
return [{
id: "group_q1",
question: `# ${industryName}面试题`,
subQuestions: questions
}];
}
return [];
}
// Function to find and replace questions for a specific industry
function replaceIndustryQuestions(content, industryName, newQuestions) {
// Find the industry section
const industryRegex = new RegExp(
`("name":\\s*"${industryName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}")`,
'g'
);
const industryMatch = industryRegex.exec(content);
if (!industryMatch) {
return null;
}
const startPos = industryMatch.index;
// Find the questions array after this industry name
const afterIndustry = content.substring(startPos);
const questionsMatch = afterIndustry.match(/"questions":\s*\[/);
if (!questionsMatch) {
return null;
}
const questionsStart = startPos + questionsMatch.index + questionsMatch[0].length;
// Find the matching closing bracket for questions array
let bracketCount = 1;
let i = questionsStart;
let inString = false;
let escapeNext = false;
while (i < content.length && bracketCount > 0) {
const char = content[i];
if (!escapeNext) {
if (char === '"' && !inString) {
inString = true;
} else if (char === '"' && inString) {
inString = false;
} else if (!inString) {
if (char === '[' || char === '{') {
bracketCount++;
} else if (char === ']' || char === '}') {
bracketCount--;
}
}
if (char === '\\') {
escapeNext = true;
}
} else {
escapeNext = false;
}
i++;
}
const questionsEnd = i - 1;
// Create the replacement string with proper indentation
const questionsStr = JSON.stringify(newQuestions, null, 2)
.split('\n')
.map(line => ' ' + line)
.join('\n');
// Replace the questions array
const newContent =
content.substring(0, questionsStart - 1) +
'\n' + questionsStr + '\n ' +
content.substring(questionsEnd + 1);
return newContent;
}
let updatedContent = mockContent;
let successCount = 0;
const failedIndustries = [];
// Process each industry
for (const [industryName, positionName] of Object.entries(industryPositionMap)) {
console.log(`Processing ${industryName}...`);
// Find interview content
const positionData = visualDesignData.find(
item => item['岗位名称'] === positionName && item['面试题内容']
);
if (!positionData) {
console.log(` ⚠️ No interview questions found for ${positionName}`);
failedIndustries.push(industryName);
continue;
}
// Extract questions
const questions = extractQuestions(positionData['面试题内容'], industryName);
if (questions.length === 0) {
console.log(` ⚠️ Could not extract questions for ${positionName}`);
failedIndustries.push(industryName);
continue;
}
// Replace questions
const newContent = replaceIndustryQuestions(updatedContent, industryName, questions);
if (newContent) {
updatedContent = newContent;
successCount++;
console.log(` ✓ Updated (using ${positionName}, ${questions[0].subQuestions.length} questions)`);
} else {
console.log(` ✗ Failed to update`);
failedIndustries.push(industryName);
}
}
// Save the updated file
fs.writeFileSync('src/mocks/resumeInterviewMock.js', updatedContent);
console.log(`\n✅ Update complete! Successfully updated ${successCount}/${Object.keys(industryPositionMap).length} industry groups`);
if (failedIndustries.length > 0) {
console.log('\n⚠ Failed industries:');
failedIndustries.forEach(name => console.log(` - ${name}`));
}
// Verify syntax
const { execSync } = require('child_process');
try {
execSync('node -c src/mocks/resumeInterviewMock.js', { encoding: 'utf-8' });
console.log('\n✅ Syntax validation passed');
// Show sample of first updated industry
if (successCount > 0) {
console.log('\n📋 Sample verification (UI设计):');
const uiMatch = updatedContent.match(/"name":\s*"UI设计"[\s\S]*?"questions":\s*\[([\s\S]*?)\]\s*}/);
if (uiMatch) {
const questionsContent = uiMatch[1];
const firstQuestion = questionsContent.match(/"question":\s*"([^"]+)"/);
if (firstQuestion) {
console.log(` First question: "${firstQuestion[1].substring(0, 50)}..."`);
}
}
}
} catch (error) {
console.error('\n❌ Syntax error detected, restoring backup...');
fs.writeFileSync('src/mocks/resumeInterviewMock.js', mockContent);
console.log('Backup restored');
console.error('Error details:', error.message);
}