Manual de usuario de calibre, Publicación 2.73.0
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):
# Try to remove the hyphen and replace the words if the resulting
# hyphen free word is recognized by the dictionary
without_hyphen = wmatch.group(1) + wmatch.group(2)
if dictionaries.recognized(without_hyphen):
return without_hyphen
return wmatch.group()
# Search for words split by a hyphen
text = replace_entities(match.group()[1:-1]) # Handle HTML entities like &
corrected = regex.sub(r'(\w+)\s*-\s*(\w+)', replace_word, text, flags=regex.
˓→VERSION1 | regex.UNICODE)
return '>%s<' % prepare_string_for_xml(corrected) # Put back required entities
Use esta función con la misma expresión de búsqueda anterior, es decir:
>[^<>]+<
Y corregirá automáticamente todas las palabras con guiones incorrectos en el el texto del libro. El truco principal es
utilizar uno de los argumentos adicionales de la función «replace»: dictionaries. Esto se refiere a los diccionarios
que el propio editor usa para comprobar la ortografía en el libro. Lo que hace esta función es buscar palabras unidas
por un guión, eliminar el guión y comprobar si el diccionario reconoce la palabra compuesta; si lo hace, las palabras
originales se sustituyen por la palabra sin guión.
Tenga en cuenta que una limitación de esta técnica es que sólo funciona par libros monolingües, porque de manera
predeterminada ‘‘dictionaries.recognized()‘‘usa el idioma principal del libro.
Enumerar secciones automáticamente
Ahora veremos algo un poco diferente. Supongamos que un archivo HTML tiene muchas secciones, cada una con
una cabecera en una etiqueta
de esta forma:
Algún texto
. Puede crear una función personalizada que numere automáticamente estas cabeceras con números consecutivos, para que tengan esta forma:
1.
Algún texto
.
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)
# Ensure that when running over multiple files, the files are processed
# in the order in which they appear in the book
replace.file_order = 'spine'
Úselo con la expresión de búsqueda:
(?s)(
]*>)(.+?
)
Coloque el cursor al principio del archivo y pulse Sustituir todo.
98
Capítulo 1. Secciones