怎么用脚本转换文档为电子书

wen 实用脚本 2

本文目录导读:

怎么用脚本转换文档为电子书

  1. 使用 Python + Calibre 工具
  2. 自定义转换脚本
  3. 批量转换脚本
  4. 命令行工具版本
  5. 安装和使用

我来介绍几种将文档转换为电子书的方法,使用Python脚本可以灵活处理各种格式。

使用 Python + Calibre 工具

安装依赖

pip install Pillow python-docx ebooklib beautifulsoup4
# 还需要安装 Calibre 的命令行工具

基本转换脚本

import os
import subprocess
from pathlib import Path
def convert_to_ebook(input_file, output_format='epub'):
    """
    使用 Calibre 的 ebook-convert 工具转换文档
    """
    input_path = Path(input_file)
    # 支持的格式
    output_file = input_path.with_suffix(f'.{output_format}')
    # 调用 Calibre 转换命令
    cmd = [
        'ebook-convert',
        str(input_path),
        str(output_file),
        '--output-profile', 'tablet',  # 针对平板优化
        '--margin-top', '20',
        '--margin-bottom', '20'
    ]
    try:
        subprocess.run(cmd, check=True)
        print(f"转换成功: {output_file}")
        return output_file
    except subprocess.CalledProcessError as e:
        print(f"转换失败: {e}")
        return None
# 使用方法
convert_to_ebook('文档.docx', 'epub')

自定义转换脚本

Word 转 EPUB

from ebooklib import epub
from docx import Document
import re
def docx_to_epub(input_file, output_file=None):
    """将 Word 文档转换为 EPUB 格式"""
    # 读取 Word 文档
    doc = Document(input_file)
    # 创建 EPUB 书籍
    book = epub.EpubBook()
    # 设置元数据
    book.set_identifier('id123456')
    book.set_title('转换文档')
    book.set_language('zh')
    book.add_author('作者')
    chapters = []
    current_chapter = []= '前言'
    for para in doc.paragraphs:
        text = para.text.strip()
        if not text:
            continue
        # 判断是否为标题
        style = para.style.name.lower()
        if 'heading' in style or 'title' in style:
            # 保存上一个章节
            if current_chapter:
                chapter_content = '\n\n'.join(current_chapter)
                epub_chapter = create_chapter(book, title, chapter_content)
                chapters.append(epub_chapter)
                current_chapter = []
            title = text
        else:
            current_chapter.append(text)
    # 保存最后一个章节
    if current_chapter:
        chapter_content = '\n\n'.join(current_chapter)
        epub_chapter = create_chapter(book, title, chapter_content)
        chapters.append(epub_chapter)
    # 添加章节到书籍
    for chapter in chapters:
        book.add_item(chapter)
    # 添加样式
    style = '''
    body { font-family: 'SimSun', serif; }
    h1 { text-align: center; }
    p { text-indent: 2em; }
    '''
    css = epub.EpubItem(uid="style", file_name="style/default.css",
                       media_type="text/css", content=style)
    book.add_item(css)
    # 设置封面
    book.toc = chapters
    # 添加导航
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    # 生成书脊
    book.spine = ['nav'] + chapters
    # 保存文件
    if not output_file:
        output_file = input_file.replace('.docx', '.epub')
    epub.write_epub(output_file, book)
    print(f"EPUB 文件已生成: {output_file}")
    return output_file
def create_chapter(book, title, content):
    """创建 EPUB 章节"""
    chapter = epub.EpubHtml(title=title, file_name=f'chapter_{len(book.items)}.xhtml',
                           lang='zh')
    # 格式化内容
    html_content = f'<h1>{title}</h1>\n<div>'
    for paragraph in content.split('\n\n'):
        if paragraph.strip():
            html_content += f'<p>{paragraph}</p>\n'
    html_content += '</div>'
    chapter.content = html_content
    return chapter
# 使用示例
docx_to_epub('示例文档.docx')

文本文件转 EPUB

def txt_to_epub(input_file, title='电子书', author='未知'):
    """将纯文本文件转换为 EPUB"""
    book = epub.EpubBook()
    book.set_identifier('id123456')
    book.set_title(title)
    book.set_language('zh')
    book.add_author(author)
    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()
    # 按章节分割
    chapters = content.split('第')
    for i, chapter_text in enumerate(chapters):
        if not chapter_text.strip():
            continue
        chapter_title = f'第{chapter_text[:10]}' if i > 0 else '前言'
        chapter = epub.EpubHtml(
            title=chapter_title,
            file_name=f'chap_{i}.xhtml',
            lang='zh'
        )
        chapter.content = f'<h1>{chapter_title}</h1><p>{chapter_text}</p>'
        book.add_item(chapter)
    # 生成文件
    output_file = input_file.replace('.txt', '.epub')
    epub.write_epub(output_file, book)
    return output_file

批量转换脚本

import os
from pathlib import Path
import concurrent.futures
def batch_convert(folder_path, output_format='epub'):
    """批量转换文件夹中的文档"""
    folder = Path(folder_path)
    supported_formats = ['.docx', '.txt', '.html', '.md']
    files_to_convert = []
    for ext in supported_formats:
        files_to_convert.extend(folder.glob(f'*{ext}'))
    def convert_file(file_path):
        try:
            if file_path.suffix == '.docx':
                docx_to_epub(str(file_path))
            elif file_path.suffix == '.txt':
                txt_to_epub(str(file_path))
            elif file_path.suffix == '.html':
                html_to_epub(str(file_path))
            elif file_path.suffix == '.md':
                md_to_epub(str(file_path))
            return f"转换成功: {file_path.name}"
        except Exception as e:
            return f"转换失败 {file_path.name}: {e}"
    # 并行处理
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        results = executor.map(convert_file, files_to_convert)
    for result in results:
        print(result)

命令行工具版本

#!/usr/bin/env python3
import argparse
import sys
def main():
    parser = argparse.ArgumentParser(description='文档转电子书工具')
    parser.add_argument('input', help='输入文件路径')
    parser.add_argument('-o', '--output', help='输出文件路径')
    parser.add_argument('-f', '--format', default='epub', 
                       choices=['epub', 'mobi', 'pdf'],
                       help='输出格式 (默认: epub)')
    parser.add_argument('--title', help='书籍标题')
    parser.add_argument('--author', help='作者')
    args = parser.parse_args()
    if not os.path.exists(args.input):
        print(f"文件不存在: {args.input}")
        sys.exit(1)
    # 根据格式选择转换方法
    if args.format == 'epub':
        docx_to_epub(args.input, args.output)
    elif args.format == 'mobi':
        # 先转epub,再用calibre转mobi
        epub_file = docx_to_epub(args.input)
        convert_to_ebook(epub_file, 'mobi')
    elif args.format == 'pdf':
        # 使用Calibre转PDF
        convert_to_ebook(args.input, 'pdf')
if __name__ == '__main__':
    main()

安装和使用

安装依赖

# 安装Python包
pip install ebooklib python-docx beautifulsoup4 markdown
# 安装Calibre (用于更多格式支持)
# Mac: brew install calibre
# Ubuntu: sudo apt-get install calibre
# Windows: 下载安装 Calibre

使用示例

# 单个文件转换
python convert.py 文档.docx -f epub -o 电子书.epub
# 批量转换
python batch_convert.py ./documents/
# 使用命令行工具
python ebook_converter.py 小说.txt --format mobi --title "我的小说" --author "作者名"

这些脚本可以帮助你将各种文档格式(Word、文本、HTML、Markdown等)转换为电子书格式(EPUB、MOBI、PDF等),根据你的具体需求选择合适的脚本即可。

抱歉,评论功能暂时关闭!