Parsing and Rebuilding EPUB Files in Python: Lessons Learned
Описание и применение
В статье описывается, как переводить EPUB‑файлы, сохраняя их структуру, используя ebooklib для чтения, lxml для точного изменения HTML и прямое изменение ZIP‑архива для сборки итогового файла.
Задача
Translating EPUBs while preserving layout, images, and styles requires precise in‑place HTML modification, which standard EPUB libraries struggle to provide.
Результат
The pipeline now reliably translates EPUBs, maintaining original layout, images, and navigation, by combining ebooklib for reading, lxml for precise HTML editing, and direct ZIP handling for final packaging.
Рабочий процесс
- Read EPUB with ebooklib
- Iterate over ITEM_DOCUMENT items
- Parse each XHTML with lxml’s HTMLParser
- Traverse tree, skip script/style, replace text nodes using a translation map
- Return modified XHTML bytes
- Extract original EPUB to temp directory
- Overwrite modified XHTML files
- Re‑zip directory ensuring 'mimetype' is first and uncompressed
- Write new EPUB
Доказательства
ebooklib’s high‑level API is designed for creating new EPUBs from scratch, not for surgical modification.
We realized we needed to treat the EPUB as a ZIP archive of XHTML files and operate directly on those files.
- Дата записи: 2026-10-21T03:41:27.382Z