View Single Post
Old 03-11-2024, 03:32 PM   #3
lomkiri
Zealot
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: 136
Karma: 1000102
Join Date: Jul 2021
Device: N/A
I found a better way for the function, with the property lastindex :
Code:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    repl = ["Mick", "Kieth", "Ronnie", "Charlie"]
    idx = match.lastindex
    return repl[idx -1]
    
    # or, if you prefer safer : return repl[idx -1] if idx <= len(repl) else match[0]
Another way, with a dict:
Code:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    equiv = {"John": "Mick", "Paul": "Kieth", "George": "Ronnie", "Ringo": "Charlie"}
    m = match[0]
    return equiv.get(m, m)    # if "m" is not in the dict, leave the text untouched
In both cases, it is possible to load the list or the dict in the function from a json file instead of defining it as a variable, maybe it was what you were thinking about? In that case, the function doesn't need to be modified at each use, only the regex and the json file.

Last edited by lomkiri; 03-12-2024 at 10:25 AM.
lomkiri is offline   Reply With Quote