使用Python的ebooklib生成EPUB时部分子章节未显示的问题
解决ebooklib生成EPUB时部分子章节未显示在目录的问题
问题原因
ebooklib对目录(TOC)的结构有严格要求:每个包含子项的章节必须以(父链接对象, 子条目序列)的元组形式定义。你当前的代码中,将1.2章节及其子项直接与1.1章节的子项并列放在Chapter1的顶层子元组中,不符合解析规则,导致这部分内容被忽略。
修正后的代码
from ebooklib import epub # Create a new EPUB book book = epub.EpubBook() # Set metadata book.set_identifier('id123456') book.set_title('book1') book.set_language('en') book.add_author('John Doe') # Create a single chapter that includes all content combined_chapter1 = epub.EpubHtml(title='Chaptor1', file_name='chapters1.xhtml', lang='en') # Add content with main chapters, sub-chapters, and sub-sub-chapters combined_chapter1.content = ''' <h1 id="chapter1">Chapter 1: Main Topic</h1> <p>Introduction to Chapter 1.</p> <h2 id="chapter1.1">1.1 Sub-Chapter</h2> <p>Content of sub-chapter 1.1.</p> <h3 id="chapter1.1.1">1.1.1 Sub-Sub-Chapter</h3> <p>Detailed content of sub-sub-chapter 1.1.1.</p> <h2 id="chapter1.2">1.2 Sub-Chapter</h2> <p>Content of sub-chapter 1.2.</p> <h3 id="chapter1.2.1">1.2.1 Sub-Sub-Chapter</h3> <p>Detailed content of sub-sub-chapter 1.2.1.</p> ''' # Add the combined chapter to the book book.add_item(combined_chapter1) # 修正后的目录结构:每个带子项的章节单独封装为元组 book.toc = ( epub.Link('chapters1.xhtml#chapter1', 'Chapter 1: Main Topic', 'chapter1'), # 1.1章节及其子项 ( epub.Link('chapters1.xhtml#chapter1.1', '1.1 Sub-Chapter', 'chapter1.1'), ( epub.Link('chapters1.xhtml#chapter1.1.1', '1.1.1 Sub-Sub-Chapter', 'chapter1.1.1'), ), ), # 1.2章节及其子项 ( epub.Link('chapters1.xhtml#chapter1.2', '1.2 Sub-Chapter', 'chapter1.2'), ( epub.Link('chapters1.xhtml#chapter1.2.1', '1.2.1 Sub-Sub-Chapter', 'chapter1.2.1'), ), ), ) # Add navigation files book.add_item(epub.EpubNcx()) nav = epub.EpubNav() book.add_item(nav) # Set the spine book.spine = ['nav', combined_chapter1] # Write the EPUB file epub.write_epub('my_book_ch1_ch2.epub', book, {})
修改说明
- 将1.2章节和它的子项
1.2.1封装为独立的嵌套元组,与1.1章节的元组同级,放在Chapter1的直接子层级中 - 确保每个父章节的子项都作为该父章节元组的第二个元素存在,符合ebooklib的目录解析逻辑
运行修正后的代码生成EPUB,用Calibre查看时,所有子章节和子子章节都会正常显示在目录中。
内容的提问来源于stack exchange,提问作者dixhom
相关产品推荐
相关产品推荐

