MCPcopy
hub / github.com/camelot-dev/camelot / text_replace

Function text_replace

camelot/utils.py:1070–1105  ·  view source on GitHub ↗

Apply key→value substring substitutions to `text`. Parameters ---------- text : str Text to process. replacements : dict[str, str] or sequence of (str, str), optional Mapping of pattern → replacement. Each key is matched as a literal substring (regex metachar

(text, replacements)

Source from the content-addressed store, hash-verified

1068
1069
1070def text_replace(text, replacements):
1071 """Apply key→value substring substitutions to `text`.
1072
1073 Parameters
1074 ----------
1075 text : str
1076 Text to process.
1077 replacements : dict[str, str] or sequence of (str, str), optional
1078 Mapping of pattern → replacement. Each key is matched as a
1079 literal substring (regex metacharacters are escaped) and every
1080 occurrence is replaced with the corresponding value. Empty
1081 keys are ignored. Falsy `replacements` returns the text
1082 unchanged. Order: when several keys could match at the same
1083 position, the longest one wins (so ``{"abc": "X", "ab": "Y"}``
1084 replaces ``"abc"`` with ``"X"`` rather than producing ``"Yc"``).
1085
1086 Returns
1087 -------
1088 str
1089 """
1090 if not replacements:
1091 return text
1092 if hasattr(replacements, "items"):
1093 items = list(replacements.items())
1094 else:
1095 items = list(replacements)
1096 # Drop empty patterns and prefer longer keys (re's alternation is
1097 # left-first, so we sort longest-first to make {"abc":"X","ab":"Y"}
1098 # behave the obvious way).
1099 items = [(k, v) for k, v in items if k]
1100 if not items:
1101 return text
1102 items.sort(key=lambda kv: len(kv[0]), reverse=True)
1103 pattern = "|".join(re.escape(k) for k, _ in items)
1104 table = dict(items)
1105 return re.sub(pattern, lambda m: table[m.group(0)], text, flags=re.UNICODE)
1106
1107
1108def text_strip(text, strip=""):

Calls

no outgoing calls