Manual de usuario de calibre, Publicación 2.73.0
Esta función usa otro de los prácticos argumentos adicionales de replace(): el argumento number. Al usar Sustituir todo, number se incrementa automáticamente en cada coincidencia.
Otra característica nueva es el uso de replace.file_order. Establecerlo en 'spine' significa que si la búsqueda se ejecuta sobre múltiples archivos HTML, los archivos se procesarán en el orden en el que aparecen en el libro.
Más detalles en Elegir un orden de archivos al ejecutar sobre múltiples archivos HTML (página 102).
Crear un índice automáticamente
Por último, vamos a intentar algo un poco más ambicioso. Supongamos que el libro tiene encabezados en etiquetas
h1 y h2 del tipo
Algún texto
. Vamos a crear un índice HTML generado automáticamente a partir de estos encabezados. Creamos la siguiente función:
from
from
from
from
calibre import replace_entities
calibre.ebooks.oeb.polish.toc import TOC, toc_to_html
calibre.gui2.tweak_book import current_container
calibre.ebooks.oeb.base import xml2str
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args,
˓→**kwargs):
if match is None:
# All matches found, output the resulting Table of Contents.
# The argument metadata is the metadata of the book being edited
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 f or ' + metadata.title, metadata.language)
print (xml2str(toc))
else:
print ('No headings to build ToC from found')
else:
# Add an entry corresponding to this match to the Table of Contents
if 'toc' not in data:
# The entries are stored in the data object, which will persist
# for all invocations of this function during a 'Replace All' operation
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() # We don't want to make any actual changes, so return
˓→the original matched text
# Ensure that we are called once after the last match is found so we can
# output the ToC
replace.call_after_last_match = True
# Ensure that when running over multiple files, this function is called,
# the files are processed in the order in which they appear in the book
replace.file_order = 'spine'
Y úselo con la expresión de búsqueda:
1.5. Modificar libros electrónicos
99