Можно ли передать словарь при замене строк в Python?

В дополнение к тому, что было сказано ранее, здесь есть функциональный способ с Рамда :

import { assocPath } from 'ramda';

const o1 = { a: { b: { c: 1 }, bb: { cc: 22 } } };
const o2 = assocPath(['a', 'b', 'c'])(42)(o1);
console.log(o1 !== o2, o1.a !== o2.a); // new copies of "changed" objects
console.log(o1.a.bb === o2.a.bb); // deep unchanged properties are copied by reference

6
задан Eric 11 August 2013 в 17:06
поделиться

2 ответа

closest is probably:

somere.sub(lambda m: replacements[m.group()], text)

for example:

>>> za = re.compile('z\w')
>>> za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu')
'fa BLU BLA bu'

with a .get instead of []-indexing if you want to supply a default for matches that are missing in replacements.

Edit: what rick really wants is to have a dict with keys to be taken as regular expression patterns, such as '\d+S', and (hopefully) constant string values (hopefully w/o backreferences). The cookbook recipe can be adapted for this purpose:

def dict_sub(d, text): 
  """ Replace in 'text' non-overlapping occurences of REs whose patterns are keys
  in dictionary 'd' by corresponding values (which must be constant strings: may
  have named backreferences but not numeric ones). The keys must not contain
  anonymous matching-groups.
  Returns the new string.""" 

  # Create a regular expression  from the dictionary keys
  regex = re.compile("|".join("(%s)" % k for k in d))
  # Facilitate lookup from group number to value
  lookup = dict((i+1, v) for i, v in enumerate(d.itervalues()))

  # For each match, find which group matched and expand its value
  return regex.sub(lambda mo: mo.expand(lookup[mo.lastindex]), text)

Example use:

  d={'\d+S': 'wot', '\d+T': 'zap'}
  t='And 23S, and 45T, and 66T but always 029S!'
  print dict_sub(d, t)

emits:

And wot, and zap, and zap but always wot!

You could avoid building lookup and just use mo.expand(d.values()[mo.lastindex-1]), but that might be a tad slow if d is very large and there are many matches (sorry, haven't precisely measured/benchmarked both approaches, so this is just a guess;-).

10
ответ дан 17 December 2019 в 04:51
поделиться

Сделать это достаточно просто:

replacements = dict(hello='goodbye', good='bad')
s = "hello, good morning";
for old, new in replacements.items():
    s = s.replace(old, new)

Вы найдете много мест, где функции PHP принимают массив значений, и нет прямого эквивалента Python, но с массивами гораздо проще работать (списки) в Python, поэтому это не проблема.

-2
ответ дан 17 December 2019 в 04:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: