View Single Post
Old 09-14-2026, 04:23 PM   #1
philja
Evangelist
philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!philja rocks like Gibraltar!
 
Posts: 435
Karma: 100100
Join Date: Nov 2015
Location: Europe EEC
Device: Kindle Fire HD6 & HD8
help on python replace function needed

Converting an epub2 to epub3, I found that another thing needing fixing was that the <title> in the <head> contained the book title rather than the Chapter title.

I made a regex Find which selected the first few lines :
Code:
(?is)(<title\b[^>]*>).*?(</title>)(.*?<h1\b[^>]*>(?:\s*<[^>]+>\s*)*([^<].+?)\s*</a></h1>)

where: 
\1 = <title>
\2 = </title>
\3 = everything after </title> up to and including </h1>
\4 = the chapter title
This worked fine because the chapter structure was consistent throughout the book. But then it occurred to me that it might be an opportunity to try a python function replace. I'm not a code writer let alone a python coder. So I took inspiration from the examples included in Sigil although I couldn't get the capitalize example function to work (lowercase, titlecase and uppercase were ok). I arrived at the following:
Code:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    title_open = match[1]
    title_close = match[2]
    between = match[3]
    chapter_title = match[4].strip()

    return title_open + chapter_title + title_close + between
This did not work, which was not really a surprise to me, but it intrigues me not to understand why.

The full regex Find/Replace works fine, but I'm sure it would be helpful to understand more about python function replace. I don't find anything in the latest downloadable user guide and what is in the online version doesn't help me, sadly.

Where did I go wrong, and any recommendations for a useful, simple and easy text on the subject?
philja is offline   Reply With Quote