Участник:Гиперболоид инженера Мошонкина/скрипт: различия между версиями

Материал из ЧТМ
Перейти к навигации Перейти к поиску
Нет описания правки
Нет описания правки
Строка 1: Строка 1:
import re
<syntaxhighlight lang="py">import re


def convert_to_lua(wiki_text):
def convert_to_lua(wiki_text):
Строка 136: Строка 136:
     # вывести в консоль print(result))
     # вывести в консоль print(result))
     print(result)
     print(result)
</syntaxhighlight>

Версия от 06:04, 24 апреля 2026

import re

def convert_to_lua(wiki_text):
    lua_output = ["return {", '    ["Tournament_Data"] = {']

    # --- 1. Парсинг групп ---
    # Регулярка ищет опциональный заголовок (; Группа X), количество команд, формат (А1/А2) и всё тело шаблона
    group_pattern = re.compile(
        r'(?:;\s*Группа\s+([^\n]+)\s*)?\{\{Группа\s+(\d+)-А(\d+)\s*\|?(.*?)\}\}', 
        re.IGNORECASE | re.DOTALL
    )

    group_counter = 1
    for match in group_pattern.finditer(wiki_text):
        group_name = match.group(1).strip() if match.group(1) else f"Unnamed_{group_counter}"
        group_counter += 1

        num_teams = int(match.group(2))
        legs_indicator = int(match.group(3))
        leg_val = 1 if legs_indicator == 2 else 0 # 1 - два круга, 0 - один

        body = match.group(4)
        # Разбиваем по пайпу и удаляем пустые элементы
        parts = [p.strip() for p in body.split('|') if p.strip()]

        teams = []
        chunk_size = num_teams + 1

        # Формируем данные команд
        for i in range(num_teams):
            chunk = parts[i * chunk_size : (i + 1) * chunk_size]
            if not chunk: continue
            status = chunk[0].replace('LY', 'L')
            name = chunk[1]
            scores = chunk[2:]
            teams.append({"name": name, "status": status, "scores": scores})

        # Записываем в формат Lua
        lua_output.append(f'\n        ["Group_{group_name}"] = {{')
        lua_output.append('            type = "group",')
        lua_output.append('            standings = {')
        for t in teams:
            lua_output.append(f'                {{"{t["name"]}", "{t["status"]}"}},')
        lua_output.append('            },')
        lua_output.append('            matches = {')

        # Распределяем матчи
        for i, team in enumerate(teams):
            score_idx = 0
            for j, opp in enumerate(teams):
                if i == j: continue # Команда не играет сама с собой
                if score_idx < len(team["scores"]):
                    score_str = team["scores"][score_idx]
                    score_idx += 1
                    if ':' in score_str:
                        g1, g2 = score_str.split(':')
                        lua_output.append(f'                {{"{team["name"]}", "{opp["name"]}", {g1.strip()}, {g2.strip()}, {leg_val}}},')

        lua_output.append('            }')
        lua_output.append('        },')

    # --- 2. Парсинг матчей на вылет ---
    # Ищет шаблоны И1, И2, И4, И7 и т.д.
    knockout_pattern = re.compile(r'\{\{И\d+\s*\|?(.*?)\}\}', re.IGNORECASE | re.DOTALL)
    ko_counter = 1

    for match in knockout_pattern.finditer(wiki_text):
        body = match.group(1)
        parts = [p.strip() for p in body.split('|') if p.strip()]

        lua_output.append(f'\n        ["Knockout_Stage_{ko_counter}"] = {{')
        lua_output.append('            type = "knockout",')
        lua_output.append('            matches = {')
        ko_counter += 1

        # Массив бьется по 5 элементов: Статус1, Команда1, Счёт, Команда2, Статус2
        for i in range(0, len(parts), 5):
            chunk = parts[i:i+5]
            if len(chunk) < 5: continue

            st1 = chunk[0].replace('LY', 'L')
            t1 = chunk[1]
            score_str = chunk[2]
            t2 = chunk[3]
            st2 = chunk[4].replace('LY', 'L')

            # Проверяем, сколько кругов (есть запятая = два круга)
            leg_val = 1 if ',' in score_str else 0
            mod = "nil"
            p1, p2 = "nil", "nil"
            base_scores = score_str

            # Парсинг доп. времени и пенальти
            if '(' in score_str:
                base_scores, ext = score_str.split('(', 1)
                ext = ext.replace(')', '').strip().lower()
                
                if 'et' in ext:
                    mod = '"aet"'
                elif 'пен' in ext:
                    mod = '"pen"'
                    pen_match = re.search(r'(\d+):(\d+)', ext)
                    if pen_match:
                        p1, p2 = pen_match.groups()

            # Считаем общую сумму голов (если матча было два)
            g1, g2 = 0, 0
            for pair in base_scores.split(','):
                if ':' in pair:
                    s1, s2 = pair.split(':')
                    g1 += int(s1.strip())
                    g2 += int(s2.strip())

            # Собираем строку
            lua_output.append(
                f'                {{"{t1}", "{t2}", {g1}, {g2}, {mod}, {p1}, {p2}, "{st1}", "{st2}", {leg_val}}},'
            )

        lua_output.append('            }')
        lua_output.append('        },')

    lua_output.append("    }")
    lua_output.append("}")
    return "\n".join(lua_output)


# --- ЗАПУСК ---
if __name__ == "__main__":
    # Сюда вставляй свой вики-код
    data = """

    """
    
    result = convert_to_lua(data)
    
    # вывести в консоль print(result))
    print(result)