133 lines
5.5 KiB
Python
133 lines
5.5 KiB
Python
import os
|
||
import re
|
||
import glob
|
||
import sys
|
||
|
||
def get_batch_size():
|
||
"""Получает размер батча из аргументов командной строки"""
|
||
batch_size = 30 # значение по умолчанию
|
||
for arg in sys.argv:
|
||
if arg.startswith('--batch='):
|
||
try:
|
||
batch_size = int(arg.split('=')[1])
|
||
print(f"Установлен размер батча: {batch_size}")
|
||
except ValueError:
|
||
print(f"Неверный аргумент: {arg}, используем значение по умолчанию: 30")
|
||
return batch_size
|
||
|
||
def clean_output_folder():
|
||
"""Очищает папку clean_events перед началом работы"""
|
||
if os.path.exists("clean_events"):
|
||
for file in os.listdir("clean_events"):
|
||
file_path = os.path.join("clean_events", file)
|
||
try:
|
||
if os.path.isfile(file_path):
|
||
os.unlink(file_path)
|
||
except Exception as e:
|
||
print(f"Ошибка при удалении {file_path}: {e}")
|
||
print("Папка clean_events очищена")
|
||
|
||
|
||
def read_file_smart(file_path):
|
||
"""Читает файл в кодировке UTF-8 или ANSI (windows-1251)"""
|
||
try:
|
||
# Пробуем UTF-8 сначала
|
||
with open(file_path, 'r', encoding='utf-8') as file:
|
||
return file.read()
|
||
except UnicodeDecodeError:
|
||
# Если не получилось, пробуем ANSI
|
||
try:
|
||
with open(file_path, 'r', encoding='windows-1251') as file:
|
||
return file.read()
|
||
except Exception as e:
|
||
print(f"Ошибка при чтении файла {file_path}: {e}")
|
||
return ""
|
||
|
||
def process_files():
|
||
|
||
clean_output_folder()
|
||
|
||
# Глобальный массив для хранения текстовой информации
|
||
global_text = []
|
||
|
||
# Получаем размер батча из аргументов
|
||
batch_size = get_batch_size()
|
||
|
||
# Массив для хранения диапазонов файлов
|
||
batch_ranges = []
|
||
|
||
# Получаем все txt-файлы в текущей папке
|
||
txt_files = glob.glob("*.txt")
|
||
|
||
# Обрабатываем группами по batch_size
|
||
for i in range(0, len(txt_files), batch_size):
|
||
batch_files = txt_files[i:i+batch_size]
|
||
|
||
# Сохраняем первый и последний файл батча
|
||
batch_ranges.append((batch_files[0], batch_files[-1]))
|
||
|
||
text_accumulator = ""
|
||
|
||
for file_name in batch_files:
|
||
print(f"Обрабатывается файл: {file_name}")
|
||
|
||
content = read_file_smart(file_name)
|
||
if not content:
|
||
continue
|
||
|
||
# Удаляем всё до -----TEXT SECTION включительно
|
||
text_section_match = re.search(r'-----TEXT SECTION\s*', content)
|
||
if text_section_match:
|
||
content = content[text_section_match.end():]
|
||
|
||
# Разделяем на строки
|
||
lines = content.split('\n')
|
||
processed_lines = []
|
||
|
||
for line in lines:
|
||
# Удаляем строки с множественными обратными слешами (более 4-5 подряд)
|
||
if re.search(r'\\\\{5,}', line):
|
||
processed_lines.append("\n_________")
|
||
continue
|
||
|
||
# Удаляем теги в квадратных скобках, кроме числовых, [name], [surname]
|
||
line = re.sub(r'\[(?!\d+\]|name\]|surname\])(.*?)\]', '', line)
|
||
|
||
processed_lines.append(line)
|
||
|
||
# Объединяем обработанные строки
|
||
processed_content = '\n'.join(processed_lines)
|
||
|
||
# Добавляем в аккумулятор
|
||
text_accumulator += f"-------- FILE: {file_name}\n"
|
||
text_accumulator += processed_content + "\n\n"
|
||
|
||
# Добавляем аккумулятор в global_text и обнуляем
|
||
if text_accumulator:
|
||
global_text.append(text_accumulator)
|
||
|
||
# Создаем папку для результатов
|
||
os.makedirs("clean_events", exist_ok=True)
|
||
|
||
# Сохраняем каждый элемент global_text в отдельный файл
|
||
for idx, text_content in enumerate(global_text):
|
||
if idx < len(batch_ranges):
|
||
first_file, last_file = batch_ranges[idx]
|
||
|
||
# Берем первые 4 символа названий файлов
|
||
first_prefix = first_file[:4] if len(first_file) >= 4 else first_file
|
||
last_prefix = last_file[:4] if len(last_file) >= 4 else last_file
|
||
|
||
output_filename = f"cl_event_{first_prefix}-{last_prefix}.txt"
|
||
output_path = os.path.join("clean_events", output_filename)
|
||
|
||
try:
|
||
with open(output_path, 'w', encoding='utf-8') as output_file:
|
||
output_file.write(text_content)
|
||
print(f"Создан файл: {output_path}")
|
||
except Exception as e:
|
||
print(f"Ошибка при сохранении файла {output_path}: {e}")
|
||
|
||
if __name__ == "__main__":
|
||
process_files()
|
||
print("Обработка завершена!") |