php - 在 Python 中替换字符串时可以传递字典吗?

标签 php python regex string

在 PHP 中,您有 preg_replace($patterns, $replacements, $string),您可以在其中通过传入模式和替换数组来一次性进行所有替换。

Python 中的等价物是什么?

我注意到 string 和 re 函数 replace()sub() 不接受字典...

根据 rick 的评论进行编辑以澄清: 这个想法是让一个带有键的字典被视为正则表达式模式,例如 '\d+S',和(希望)常量字符串值(希望没有反向引用)。现在相应地编辑我的答案(即回答实际问题)。

最佳答案

最接近的可能是:

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

例如:

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

使用 .get 而不是 []-indexing 如果你想为 replacements 中缺失的匹配项提供默认值。

编辑:rick 真正想要的是有一个字典,其中的键被视为正则表达式模式,例如 '\d+S',以及(希望)常量字符串值(希望 w/o 反向引用)。食谱食谱可以为此目的进行调整:

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)

使用示例:

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

发出:

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

您可以避免构建 lookup 并只使用 mo.expand(d.values()[mo.lastindex-1]),但这可能有点慢如果 d 非常大并且有很多匹配项(抱歉,还没有对这两种方法进行精确测量/基准测试,所以这只是一个猜测;-)。

关于php - 在 Python 中替换字符串时可以传递字典吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/937697/

相关文章:

regex - 获得字素的正确方法是什么?

javascript - 正则表达式:匹配模式,但前面的模式除外

php - 为 Zend 应用程序提供数据库处理程序的 "right"方法是什么

python - 如何使用 sleep 来限制写入日志的数据?

python - 将元组列表转换为字典,给每个元组一个不同的键

python re invalid group reference\10\2

java - 使用正则表达式获取匹配字符串的索引

php - fsockopen 有错误 : HTTP/1. 1 301 Moved Permanently 和 404

php - 如何开始使用 php/mysql/jquery 中的饮食记录脚本

javascript - 将动词表数据导入 html/css 表