/
erioxis
/
web-nodejs
Обзор
Документация
Войти
/
erioxis
/
web-nodejs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
backend/src/services/lab8/task2.service.js
207 строк
7 KB
erioxis
lab11fix
15 дек 2025, 23:21
15 дек 2025, 23:21
70dc7ba
Код
Авторство
О чём код?
// backend/src/services/lab8/task2.service.js import fs from 'fs/promises'; import path from 'path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // Пути к файлам const sourceFilePath = path.join(__dirname, '..', '..', '..', 'data', 'lab8', 'task2', 'cup.txt'); const groupsOutputPath = path.join(__dirname, '..', '..', '..', 'data', 'lab8', 'task2', 'groups.json'); const stadiumOutputPath = path.join(__dirname, '..', '..', '..', 'data', 'lab8', 'task2', 'stadium.json'); const dataDirPath = path.dirname(groupsOutputPath); class Task2Service { async ensureDataDir() { try { await fs.mkdir(dataDirPath, { recursive: true }); console.log(`Папка данных создана: ${dataDirPath}`); } catch (error) { console.error(`Ошибка при создании папки ${dataDirPath}:`, error); throw error; } } async loadSourceFile() { try { console.log(`Чтение файла: ${sourceFilePath}`); const data = await fs.readFile(sourceFilePath, 'utf8'); console.log(`Файл прочитан успешно. Размер: ${data.length} символов`); return data; } catch (error) { console.error(`Ошибка при чтении файла ${sourceFilePath}:`, error); if (error.code === 'ENOENT') { throw new Error(`Исходный файл ${sourceFilePath} не найден. Убедитесь, что он загружен.`); } throw error; } } parseCupData(text) { console.log('Начинаем парсинг данных...'); const lines = text.split('\n'); const matches = []; let currentGroup = null; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); // Пропускаем пустые строки if (!line) continue; // Определяем группу if (line.startsWith('Group') && line.length === 7) { currentGroup = line.charAt(6); // Берем букву после "Group " console.log(`Обнаружена группа: ${currentGroup}`); continue; } // Ищем матчи в формате "(номер) ДД Мес/ГГ ЧЧ:ММ Команда1 счет (счет в перерыве) Команда2 @ Стадион, Место" const matchRegex = /^\((\d+)\)\s+(\w+\s+\w+\/\d{2})\s+(\d{2}:\d{2})\s+([A-Za-z\s]+)\s+(\d+-\d+)\s+\((\d+-\d+)\)\s+([A-Za-z\s]+)\s+@\s+([A-Za-z\s,]+)$/; const matchLine = matchRegex.exec(line); if (matchLine) { const matchNumber = matchLine[1]; const dateInfo = matchLine[2]; const time = matchLine[3]; const team1 = matchLine[4].trim(); const fullScore = matchLine[5]; const halfTimeScore = matchLine[6]; const team2 = matchLine[7].trim(); const stadiumInfo = matchLine[8].trim(); // Разделяем дату на компоненты const dateParts = dateInfo.split(' '); const day = dateParts[0]; const monthDay = dateParts[1]; // Например, "Nov/20" // Извлекаем название стадиона и город const stadiumParts = stadiumInfo.split(','); const stadiumName = stadiumParts[0].trim(); const city = stadiumParts[1] ? stadiumParts[1].trim() : ''; const match = { matchNumber, group: currentGroup, date: monthDay.replace('/', '.'), // Преобразуем в формат "Nov.20" time, team1, score: fullScore, halfTimeScore, team2, stadium: stadiumName, city }; console.log(`Добавлен матч: ${match.group} ${match.date} ${match.team1} vs ${match.team2}`); matches.push(match); } } console.log(`Парсинг завершен. Всего найдено матчей: ${matches.length}`); return matches; } groupMatchesByGroup(matches) { console.log('Группировка матчей по группам...'); const grouped = {}; matches.forEach(match => { if (!grouped[match.group]) { grouped[match.group] = []; } grouped[match.group].push(match); }); console.log(`Сгруппировано по группам: ${Object.keys(grouped).length} групп`); return grouped; } groupMatchesByStadium(matches) { console.log('Группировка матчей по стадионам...'); const grouped = {}; matches.forEach(match => { if (!grouped[match.stadium]) { grouped[match.stadium] = []; } grouped[match.stadium].push(match); }); console.log(`Сгруппировано по стадионам: ${Object.keys(grouped).length} стадионов`); return grouped; } async saveToFile(filePath, data) { await this.ensureDataDir(); console.log(`Сохранение данных в файл: ${filePath}`); try { await fs.writeFile(filePath, JSON.stringify(data, null, 2), 'utf8'); console.log(`Данные успешно сохранены в ${filePath}`); } catch (error) { console.error(`Ошибка при записи в файл ${filePath}:`, error); throw error; } } async processAndSave() { try { console.log('=== НАЧАЛО ОБРАБОТКИ ДАННЫХ ==='); const text = await this.loadSourceFile(); const matches = this.parseCupData(text); if (matches.length === 0) { console.error('Не удалось найти ни одного матча в файле!'); throw new Error('Парсинг не обнаружил матчей в файле cup.txt. Проверьте формат файла.'); } const byGroup = this.groupMatchesByGroup(matches); const byStadium = this.groupMatchesByStadium(matches); await this.saveToFile(groupsOutputPath, byGroup); await this.saveToFile(stadiumOutputPath, byStadium); console.log('=== ОБРАБОТКА ДАННЫХ ЗАВЕРШЕНА ==='); return { groups: byGroup, stadiums: byStadium, totalMatches: matches.length }; } catch (err) { console.error('КРИТИЧЕСКАЯ ОШИБКА ПРИ ОБРАБОТКЕ:', err); throw err; } } async getGroups() { try { console.log(`Загрузка данных из файла групп: ${groupsOutputPath}`); const data = await fs.readFile(groupsOutputPath, 'utf8'); return JSON.parse(data); } catch (error) { console.error(`Ошибка при чтении файла групп:`, error); if (error.code === 'ENOENT') { return {}; } throw error; } } async getStadiums() { try { console.log(`Загрузка данных из файла стадионов: ${stadiumOutputPath}`); const data = await fs.readFile(stadiumOutputPath, 'utf8'); return JSON.parse(data); } catch (error) { console.error(`Ошибка при чтении файла стадионов:`, error); if (error.code === 'ENOENT') { return {}; } throw error; } } } export default new Task2Service();