返回

, author, content): # 创建 epub 文件 epub = zipfile.ZipFile('my_book.epub', 'w') # 创建目录文件 manifest = ET.Element('manifest') # 创建内容文件 content_file = ET.Element('item', id='content', href='content.html') manifest.append(content_file) # 创建内容页面 content_html = '<html><head>' + title + '

前端

从命令行自动生成电子书(续)

前言

在先前的文章中,我们手动构建了 .epub 的基本文件内容,并确定了可以自动化完成的任务。现在,我们将开始编码,利用 Python 实现电子书生成自动化。

Python 实现

import os
import zipfile
import lxml.etree as ET

def create_epub(title, author, content):
    # 创建 epub 文件
    epub = zipfile.ZipFile('my_book.epub', 'w')
    
    # 创建目录文件
    manifest = ET.Element('manifest')
    
    # 创建内容文件
    content_file = ET.Element('item', id='content', href='content.html')
    manifest.append(content_file)
    
    # 创建内容页面
    content_html = '<html><head></head><body>' + content + '</body></html>'
    
    # 添加内容文件到 epub
    epub.writestr('content.html', content_html.encode('utf-8'))
    
    # 创建 metadata.opf 文件
    metadata = ET.Element('package', xmlns='http://www.idpf.org/2007/opf')
    metadata.set('version', '2.0')
    
    # 添加标题和作者信息
    metadata.append(ET.Element('title') + title)
    metadata.append(ET.Element('creator') + author)
    
    # 添加清单文件
    metadata.append(manifest)
    
    # 将 metadata.opf 文件添加到 epub
    epub.writestr('metadata.opf', ET.tostring(metadata, encoding='utf-8'))
    
    # 添加封面图片
    epub.write('cover.jpg')
    
    # 添加 CSS 样式表
    epub.write('style.css')
    
    # 关闭 epub 文件
    epub.close()

# 使用示例
create_epub('My Book', 'Author Name', 'This is the content of my book.')

封装的元素: