头图

一个令人惊呆的 epub3 模块

python-epub3 是一个用于管理 ePub 3 书籍的 Python 库。

提醒⏰ 目前正在开发中,暂时不要在生产环境中使用。

安装

通过 github 安装:

pip install git+https://github.com/ChenyangGao/python-epub3

通过 pypi 安装:

pip install python-epub3

快速开始

>>> # 导入模块
>>> from epub3 import ePub
>>> # 创建一本电子书,可以接受一个实际存在的电子书路径
>>> book = ePub()
>>> book
<{http://www.idpf.org/2007/opf}package>{'version': '3.0', 'unique-identifier': 'BookId'}
>>> # 查看元数据
>>> book.metadata
<{http://www.idpf.org/2007/opf}metadata>
[<{http://purl.org/dc/elements/1.1/}identifier>{'id': 'BookId'} text='urn:uuid:d6cc8f4a-d489-47c9-8b69-97dd597e02c3',
 <{http://purl.org/dc/elements/1.1/}language> text='en',
 <{http://purl.org/dc/elements/1.1/}title>,
 <{http://www.idpf.org/2007/opf}meta>{'property': 'dcterms:modified'} text='2023-11-21T16:55:42Z']
>>> # 修改 dc:title
>>> book.title = "my book"
>>> # 修改 dc:language
>>> book.language = "zh-CN"
>>> # 更新修改时间
>>> book.modified
'2023-11-21T16:56:23Z'
>>> # 再次查看元数据
>>> book.metadata
<{http://www.idpf.org/2007/opf}metadata>
[<{http://purl.org/dc/elements/1.1/}identifier>{'id': 'BookId'} text='urn:uuid:d6cc8f4a-d489-47c9-8b69-97dd597e02c3',
 <{http://purl.org/dc/elements/1.1/}language> text='zh-CN',
 <{http://purl.org/dc/elements/1.1/}title> text='my book',
 <{http://www.idpf.org/2007/opf}meta>{'property': 'dcterms:modified'} text='2023-11-21T16:56:23Z']
>>> # 添加一个路径
>>> item = book.manifest.add("index.xhtml")
>>> item
<Item({'id': '6053413d-b534-4409-9e9f-7a5cf0a74da9', 'href': 'index.xhtml', 'media-type': 'application/xhtml+xml'}) at 0x1066e75d0>
>>> # 把上面的文件添加到 spine 中
>>> book.spine.add(item.id)
<Itemref({}) at 0x1076de2d0>
>>> # 打开文件,并写入一些数据
>>> file = item.open("w")
>>> file.write('''<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html>
... <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
... <head>
...   <title></title>
... </head>
... <body>
...   <p>&#160;</p>
... </body>
... </html>''')
211
>>> file.close()
>>> # 添加一个路径,并且关联一个外部路径
>>> item = book.manifest.add("cover.png", "/path/to/cover.png")
>>> item
<Item({'id': '35f19873-121d-42f9-9d56-e99cdac7d885', 'href': 'cover.png', 'media-type': 'image/png'}) at 0x1066f5850>
>>> # 设置封面
>>> book.cover = item.id
>>> book.cover
'35f19873-121d-42f9-9d56-e99cdac7d885'
>>> # 通过函数来获取 meta 元数据项
>>> book.metadata.meta('[@name="cover"]')
<{http://www.idpf.org/2007/opf}meta>{'name': 'cover', 'content': '35f19873-121d-42f9-9d56-e99cdac7d885'}
>>> # 通过函数来获取 dc 元数据项
>>> book.metadata.dc("title")
<{http://purl.org/dc/elements/1.1/}title> text='my book'
>>> # 打包电子书
>>> book.pack("book.epub")

文档

https://python-epub3.readthedocs.io

麻花疼
1 声望1 粉丝

The Zen of Python