Загаловками глав в исходном файле будут считаться строки начинающиеся со слова "Глава".
Запускать:
python make_fb2.py --input_file file_to_translate.txt
import argparse
import time
import datetime
import asyncio
async def main(input_file):
current_date = datetime.date.today()
#Заголовок FB2 файла
hdr = f"""<?xml version="1.0" encoding="UTF-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
<description>
<title-info>
<genre>Жанр</genre>
<author><first-name></first-name><last-name>Имя автора</last-name></author>
<book-title>{input_file}</book-title>
<coverpage><image l:href="#img_0"/></coverpage>
<lang>en</lang>
</title-info>
<document-info>
<author><first-name></first-name><last-name>a1999</last-name></author>
<program-used>Python</program-used>
<date>{current_date}</date>
<id>6b7fd645-d6c3-48a4-b4dd-f72e6a6d478b</id>
<version>1.0</version>
</document-info>
<publish-info>
<year>2025</year>
</publish-info>
</description>
<body>"""
ftr = f""" </section>
</body>
</FictionBook>
"""
import os
base_name = os.path.splitext(os.path.basename(input_file))[0]
file_o = open(base_name + '.fb2', 'w', encoding='utf-8')
first = 0
file_o.write(hdr)
with open(input_file, 'r', encoding="utf-8") as file:
chapter_count = 0 # Инициализируем счетчик глав
first = 0
while True:
line = file.readline()
if not line:
break
line = line.strip()
if line != '':
if line.startswith('Глава'):
chapter_count += 1 # Увеличиваем номер при каждой новой главе
# Формируем строку с номером.
# replace('Глава', f'Глава {chapter_count}', 1) заменит только первое вхождение
line_with_number = line.replace('Глава', f'Глава {chapter_count}', 1)
#line_with_number = line
if first != 0:
file_o.write('</section>\n')
first = 1
file_o.write('<section>\n')
file_o.write('<title>\n')
file_o.write(f'<p>{line_with_number}</p>\n')
file_o.write('</title>\n')
else:
file_o.write(f'<p>{line}</p>\n')
#process_data(data_buffer+line)
file_o.write(ftr)
file_o.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Process and translate chunks of text.")
parser.add_argument("--input_file", required=True, help="Path to the input text file.")
args = parser.parse_args()
asyncio.run(main(args.input_file))
