首页
/ Debian-Calibre/Calibre 编辑器中的函数模式高级搜索替换指南

Debian-Calibre/Calibre 编辑器中的函数模式高级搜索替换指南

2025-07-10 02:46:21作者:晏闻田Solitary

什么是函数模式?

在 Debian-Calibre/Calibre 电子书编辑器中,搜索替换工具提供了一个强大的函数模式。这个模式允许你将正则表达式与 Python 函数结合使用,实现各种高级文本处理功能。

与普通正则表达式替换不同,函数模式不是使用固定模板进行替换,而是通过 Python 函数动态生成替换内容。这为文本处理提供了无限可能性。

函数模式的基本结构

所有函数模式的 Python 函数都必须遵循以下基本结构:

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    # 处理逻辑
    return "替换后的文本"

实用案例解析

案例1:自动修正标题大小写

问题:电子书中的标题大小写不规范,需要统一为标题格式。

解决方案

# 使用内置的标题格式函数
Find expression: <([Hh][1-6])[^>]*>.+?</\1>

这个正则表达式匹配所有 h1-h6 标签,内置函数会自动将内容转换为标题格式(首字母大写)。

案例2:智能替换连字符为破折号

问题:电子书中使用了简单的连字符(-)而不是标准的破折号(—)。

自定义函数

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    return match.group().replace('--', '—').replace('-', '—')

使用方式

Find expression: >[^<>]+<

这个函数会先替换双连字符(--),再替换单连字符(-),但不会影响HTML标签内的内容。

案例3:修复错误断词

问题:扫描版电子书中常有因换行导致的错误断词(如"ele-phant")。

高级解决方案

import regex
from calibre import replace_entities
from calibre import prepare_string_for_xml

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    def replace_word(wmatch):
        without_hyphen = wmatch.group(1) + wmatch.group(2)
        if dictionaries.recognized(without_hyphen):
            return without_hyphen
        return wmatch.group()
    
    text = replace_entities(match.group()[1:-1])
    corrected = regex.sub(r'(\w+)\s*-\s*(\w+)', replace_word, text, flags=regex.VERSION1 | regex.UNICODE)
    return '>%s<' % prepare_string_for_xml(corrected)

这个函数会检查断词合并后是否在词典中存在,如果存在则自动合并。

高级功能详解

1. 自动编号章节

通过利用 number 参数,可以实现章节自动编号:

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    section_number = '%d. ' % number
    return match.group(1) + section_number + match.group(2)

replace.file_order = 'spine'

2. 自动生成目录

更复杂的例子是自动从标题生成目录:

from calibre import replace_entities
from calibre.ebooks.oeb.polish.toc import TOC, toc_to_html
from calibre.gui2.tweak_book import current_container
from calibre.ebooks.oeb.base import xml2str

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    if match is None:
        if 'toc' in data:
            toc = data['toc']
            root = TOC()
            for (file_name, tag_name, anchor, text) in toc:
                parent = root.children[-1] if tag_name == 'h2' and root.children else root
                parent.add(text, file_name, anchor)
            toc = toc_to_html(root, current_container(), 'toc.html', 'Table of Contents for ' + metadata.title, metadata.language)
            print(xml2str(toc))
    else:
        if 'toc' not in data:
            data['toc'] = []
        tag_name, anchor, text = match.group(1), replace_entities(match.group(2)), replace_entities(match.group(3))
        data['toc'].append((file_name, tag_name, anchor, text))
        return match.group()

replace.call_after_last_match = True
replace.file_order = 'spine'

函数参数详解

  1. match对象:包含匹配到的文本和分组信息
  2. number:当前匹配的序号(从1开始)
  3. file_name:匹配所在的文件名
  4. metadata:电子书的元数据(标题、作者等)
  5. dictionaries:拼写检查词典
  6. data:持久化数据存储(在整个替换过程中共享)
  7. functions:访问其他自定义函数

调试技巧

在函数中使用 print() 输出调试信息,这些信息会在替换完成后显示在弹出窗口中。

最佳实践建议

  1. 对于简单替换,优先使用内置函数
  2. 复杂处理时,合理利用 data 对象保存中间状态
  3. 多文件处理时设置 file_order = 'spine' 保持顺序
  4. 需要最终汇总时使用 call_after_last_match = True

通过掌握这些高级功能,你可以极大地提升电子书编辑效率,实现各种复杂的自动化处理需求。

登录后查看全文
热门项目推荐