View Single Post
Old 03-21-2024, 12:19 PM   #23
lomkiri
Groupie
lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.lomkiri ought to be getting tired of karma fortunes by now.
 
lomkiri's Avatar
 
Posts: 172
Karma: 1497966
Join Date: Jul 2021
Device: N/A
It's because you should have adapted the code.

1) The line "return data['equiv'].get(m, m)" is from the old code, it was not to be included.
2) In this code, the dict is loaded in data['equiv'], not in equiv, so you'll have to adapt the new code to this fact (the reason I've loaded it in data is that, doing this, it's necessary to load the json only once for all passages)
3) Since you're loading one whole page, it's normal that there is only one change. The regex system counts the times it takes an expression (a page, in this case). It will count a change even if there is no change in the page (it has no way to know if the "m" you return has been modified).
If you've got 5 pages, it will give you 5 changes, even if you have 100 changes in the 1st page, and none in the other 4 pages.
Click in "See modifications" to see the real changes.
4) If you want to know how many changes have been made, you'll have to use subn(), not sub(), and must increment a counter in data['counts'], and "print" this counter during the last passage (ask if you need it and you don't know how to do that).


The code (tested) is :
Code:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    from calibre.utils.config import JSONConfig
    import regex

    # Load json only at first passage
    # data will retain its values throught all passages when "replace all"
    if number == 1:
        fname = 'beastones.json'
        data['equiv'] = JSONConfig(fname)
        if not data['equiv']:
            print(f'Problem loading {fname}, no treatment will be done')
            
    # normal passage
    m = match.group() 
    for key, val in data['equiv'].items():
        m = regex.sub(rf'\b{key}\b', val, m)
    return m
The json file (beastones.json, in this case, change fname if you choose another filename) must be in the config folder of calibre, and must contain :
Code:
{
  "John": "Mike",
  "Paul": "Keith",
  "George": "Ronnie",
  "Ringo": "Charlie"
}

Last edited by lomkiri; 03-22-2024 at 07:16 PM. Reason: screenshot removed
lomkiri is offline   Reply With Quote