View Single Post
Old 03-11-2024, 02:38 PM   #2
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: 167
Karma: 1497966
Join Date: Jul 2021
Device: N/A
Quote:
Originally Posted by moldy View Post
However when I run the search it gives the error:
TypeError: unhashable type: 'list'
You get this error because you pass a list where it expects a string.
I don't know how to do this in mode regex, but in mode function I'll do it this way :

Code:
      [...]
      "find": "(John)|(Paul)|(George)|(Ringo)",
      "mode": "function",
      [...]
and the function (edit: see next msg for a better code) :
Code:
def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):
    repl = ["Mick", "Kieth", "Ronnie", "Charlie"]
    len_match = len(match)

    for i in range(1, len_match):
        if match[i]:
            return repl[i-1] if i <= len(repl) else match[0]
Explanation :
If we find "Paul", it will be in the 2nd capturing group (i.e. match[2], the other groups will be None), so we return the 2nd name of the list "repl", i.e. repl[1].

If "repl" is, by mistake, smaller than the number of the capturing groups, we avoid an exception not doing anything (returns match[0])

If you're sure of the exact correspondence of the lists in and out, you can just put
return repl[i-1]
it will be quicker if there are lots of occurrences

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