Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

Parsing and Rebuilding EPUB Files in Python: Lessons Learned

说明与用途

文章说明如何在保持布局的前提下翻译EPUB文件,使用ebooklib读取,lxml编辑HTML,并通过直接ZIP操作重建EPUB。

问题

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