fledermaus/table_handler/commands/find_and_replace.py

20 lines
664 B
Python

import re
from copy import deepcopy
class FindAndReplace:
def __init__(self, map: dict[str, list[str]], case_sensitive: bool = False):
self.map = map
self.case_sensitive = case_sensitive
def execute_on_cell(self, entry) -> str:
res = deepcopy(entry.value)
for species, alternatives in self.map.items():
for old_version in alternatives:
if self.case_sensitive:
res = res.replace(old_version, species)
else:
pattern = re.compile(re.escape(old_version), re.IGNORECASE)
res = pattern.sub(species, res)
return res