/
suhareva
/
web-nodejs-labs
Обзор
Документация
Войти
/
suhareva
/
web-nodejs-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
backend/src/services/lab8/task2.parser.js
155 строк
6 KB
koyo
feat(lab1): Finish lab1 static page
25 ноя 2025, 19:23
25 ноя 2025, 19:23
9fb805d
Код
Авторство
О чём код?
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 basePath = path.join(__dirname, '..', '..', '..', 'data', 'lab8', 'task2'); const cupPath = path.join(basePath, 'cup.txt'); const groupsJson = path.join(basePath, 'groups.json'); const stadiumJson = path.join(basePath, 'stadium.json'); async function parseCupTxt() { try { await fs.mkdir(basePath, { recursive: true }); const cup = await fs.readFile(cupPath, 'utf8'); console.log('cup.txt загружен, длина:', cup.length); // Парсинг групп и команд const groups = {}; const groupLines = cup.split('\n').filter(line => line.includes('Group') && line.includes('|')); for (const line of groupLines) { const m = line.match(/Group ([A-H])\s+\|\s+(.+)/); if (!m) continue; const groupName = `Group ${m[1]}`; const teams = m[2].split(/\s{2,}/).map(t => t.trim()).filter(Boolean); groups[groupName] = { teams, matches: [] }; console.log(`Группа ${groupName}: команды`, teams); } const stadiums = {}; // Проходим по всем строкам файла и определяем текущую группу const lines = cup.split('\n'); let currentGroup = ''; for (const line of lines) { const trimmed = line.trim(); // Если нашли заголовок группы, обновляем текущую группу const groupMatch = trimmed.match(/^Group ([A-H])$/); if (groupMatch) { currentGroup = `Group ${groupMatch[1]}`; console.log(`\nТекущая группа: ${currentGroup}`); continue; } // Если строка начинается с номера матча и у нас есть текущая группа if (/^\(\d+\)/.test(trimmed) && currentGroup && groups[currentGroup]) { console.log('Парсинг строки матча:', trimmed); // Упрощенное регулярное выражение для парсинга матчей const matchRegex = /\((\d+)\)\s+(.+?)\s+(\d+)-(\d+)(?:\s+\(\d+-\d+\))?\s+(.+?)\s+@\s+([^,]+),\s+(.+)/; const m = trimmed.match(matchRegex); if (!m) { console.log('Строка не совпадает с шаблоном:', trimmed); continue; } const [, num, team1Part, score1, score2, team2, stadium, city] = m; // Извлекаем название первой команды (убираем дату) const team1 = team1Part.replace(/[A-Za-z]+\s+[A-Za-z]+\/\d+\s+\d+:\d+/, '').trim(); // Для groups.json - сохраняем ТОЛЬКО номер, команды и счет (без стадиона и города) const matchForGroup = { num: Number(num), team1: team1, score1: Number(score1), score2: Number(score2), team2: team2.trim() }; // Добавляем матч в группу (только основные данные) groups[currentGroup].matches.push(matchForGroup); console.log(`Матч добавлен в группу ${currentGroup}:`, `${matchForGroup.team1} ${matchForGroup.score1}-${matchForGroup.score2} ${matchForGroup.team2}`); // Для stadium.json - извлекаем дату и время отдельно const dateTimeMatch = team1Part.match(/([A-Za-z]+\s+[A-Za-z]+\/\d+)\s+(\d+:\d+)/); let date = ''; let time = ''; if (dateTimeMatch) { date = dateTimeMatch[1]; // "Sun Nov/20" time = dateTimeMatch[2]; // "19:00" } // Добавляем матч на стадион (с датой, временем, стадионом и городом) const stadiumKey = `${stadium.trim()}, ${city.trim()}`; if (!stadiums[stadiumKey]) { stadiums[stadiumKey] = []; } // Сохраняем полную информацию о матче для стадиона stadiums[stadiumKey].push({ group: currentGroup, num: Number(num), date: date, time: time, team1: team1, score1: Number(score1), score2: Number(score2), team2: team2.trim(), stadium: stadium.trim(), city: city.trim() }); console.log(`Матч добавлен на стадион: ${stadiumKey}`, { date: date, time: time }); } } await fs.writeFile(groupsJson, JSON.stringify(groups, null, 2), 'utf8'); await fs.writeFile(stadiumJson, JSON.stringify(stadiums, null, 2), 'utf8'); console.log('\ngroups.json и stadium.json успешно созданы'); console.log('Группы созданы:', Object.keys(groups)); console.log('Стадионы созданы:', Object.keys(stadiums)); // Статистика let totalMatches = 0; Object.keys(groups).forEach(group => { const matchCount = groups[group].matches.length; totalMatches += matchCount; console.log(` ${group}: ${matchCount} матчей`); }); console.log(`Всего матчей: ${totalMatches}`); // Покажем пример данных console.log('\nПример из groups.json:'); const firstGroup = groups[Object.keys(groups)[0]]; if (firstGroup && firstGroup.matches.length > 0) { console.log(JSON.stringify(firstGroup.matches[0], null, 2)); } console.log('\nПример из stadium.json:'); const stadiumKeys = Object.keys(stadiums); if (stadiumKeys.length > 0) { const firstStadium = stadiums[stadiumKeys[0]]; if (firstStadium.length > 0) { console.log(JSON.stringify(firstStadium[0], null, 2)); } } } catch (err) { console.error('Ошибка парсинга:', err); } } parseCupTxt();