stb/index.js
2024-11-07 14:21:20 +08:00

149 lines
4.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs = require('fs');
const mysql = require('mysql2/promise');
const dbConfig = {
host: 'localhost',
user: 'root',
password: '123456',
database: 'stb2'
};
function convertAnswerToNumber(answer, type) {
const answerMap = {
'A': 0, 'a': 0,
'B': 1, 'b': 1,
'C': 2, 'c': 2,
'D': 3, 'd': 3,
'E': 4, 'e': 4,
'F': 5, 'f': 5,
'G': 6, 'g': 6,
'H': 7, 'h': 7,
'I': 8, 'i': 8,
'J': 9, 'j': 9
};
if (!answer) return type === 'checkbox' ? [] : 0;
if (type === 'checkbox') {
return answer.split('').map(letter => {
if (['对', '正确', 'T', 'TRUE'].includes(letter)) return 0;
if (['错', '错误', 'F', 'FALSE'].includes(letter)) return 1;
return answerMap[letter] ?? 0;
});
} else {
if (['对', '正确', 'T', 'TRUE'].includes(answer)) return 0;
if (['错', '错误', 'F', 'FALSE'].includes(answer)) return 1;
return answerMap[answer] ?? 0;
}
}
function formatOption(index, value, type) {
if (!value) return `${String.fromCharCode(65 + index)}.`;
if (type === 'radio' && value.match(/^(对|错|正确|错误|TRUE|FALSE|T|F)$/i)) {
return [`A.正确`, `B.错误`];
}
return `${String.fromCharCode(65 + index)}.${value.trim()}`;
}
function convertQuestionType(type) {
if (!type) return 'radio';
if (type.includes('单选')) {
return 'radio';
} else if (type.includes('多选')) {
return 'checkbox';
} else if (type.includes('判断')) {
return 'radio';
}
return 'radio';
}
async function insertData() {
const connection = await mysql.createConnection(dbConfig);
const content = fs.readFileSync('华为ICT题库提取版.txt', 'utf8');
const questions = content.split('\n\n');
try {
await connection.beginTransaction();
const topicIds = [];
for(const questionBlock of questions) {
if(!questionBlock.trim()) continue;
const lines = questionBlock.split('\n').filter(line => line.trim());
if(lines.length < 4) continue;
const title = lines[0].replace(/^题目\d+/, '').trim() || '未知题目';
const originalType = lines[1].replace('题目类型:', '').trim();
const type = convertQuestionType(originalType);
const optionsStartIndex = lines.findIndex(line => line === '选项:');
const optionsEndIndex = lines.findIndex(line => line.startsWith('答案:'));
if(optionsStartIndex === -1 || optionsEndIndex === -1) continue;
const optionsRaw = lines.slice(optionsStartIndex + 1, optionsEndIndex)
.filter(line => line.trim());
let options;
if (type === 'radio' && originalType.includes('判断')) {
options = ['A.正确', 'B.错误'];
} else {
options = optionsRaw.map((line, index) => {
const [, ...valueParts] = line.split(/[A-Za-z]\.\s*/);
return formatOption(index, valueParts.join(''), type);
}).filter(Boolean);
}
if (!options || options.length === 0) {
options = ['A.选项1'];
}
const answerLetter = lines[optionsEndIndex]?.replace('答案:', '').trim();
const answer = convertAnswerToNumber(answerLetter, type);
const [topicResult] = await connection.execute(
'INSERT INTO topics (title, type, answer, options) VALUES (?, ?, ?, ?)',
[
title,
type,
JSON.stringify(answer),
JSON.stringify(options)
]
);
topicIds.push(topicResult.insertId);
}
if (topicIds.length === 0) {
throw new Error('No valid topics were processed');
}
const [paperResult] = await connection.execute(
'INSERT INTO paper (title, description, TopicsId, date, state, userId) VALUES (?, ?, ?, NOW(), 1, ?)',
[
'华为ICT基础软件赛道真题题库',
'2024-2025年最新华为ICT基础软件赛道真题题库-带解析版',
JSON.stringify(topicIds),
'admin'
]
);
await connection.commit();
console.log('数据插入成功!');
} catch (error) {
await connection.rollback();
console.error('数据插入失败:', error);
console.error('错误详情:', error.stack);
throw error;
} finally {
await connection.end();
}
}
insertData().catch(err => {
console.error('程序失败:', err);
process.exit(1);
});