Total Complexity | 8 |
Total Lines | 42 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | import re |
||
|
|||
2 | from pathlib import Path |
||
3 | from typing import Mapping |
||
4 | |||
5 | from mandos.model import MandosResources |
||
6 | |||
7 | |||
8 | class RegexMap: |
||
9 | def __init__(self, dct: Mapping[re.Pattern, str]): |
||
10 | self._dct = dct |
||
11 | |||
12 | def get(self, s: str) -> str: |
||
13 | for pat, fixed in self._dct.items(): |
||
14 | sub = pat.sub(fixed, s) |
||
15 | if sub != s: |
||
16 | return sub |
||
17 | return s |
||
18 | |||
19 | |||
20 | class RegexMapParser: |
||
21 | @classmethod |
||
22 | def from_resource(cls, name: str): |
||
23 | return cls.from_path(MandosResources.path("mappings", name, suffix=".regexes")) |
||
24 | |||
25 | @classmethod |
||
26 | def from_path(cls, path: Path): |
||
27 | dct = {} |
||
28 | for line in path.read_text(encoding="utf8").splitlines(): |
||
29 | if not line.startswith("#"): |
||
30 | key, value = line.split("--->") |
||
31 | key, value = key.strip(), value.strip() |
||
32 | dct[re.compile(key)] = value |
||
33 | return RegexMap(dct) |
||
34 | |||
35 | |||
36 | if __name__ == "__main__": |
||
37 | mp = RegexMapParser.from_resource("@targets_neuro.regex") |
||
38 | print(mp.get("Dopamine D3 receptor")) |
||
39 | |||
40 | |||
41 | __all__ = ["RegexMap", "RegexMapParser"] |
||
42 |