【问题标题】:Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python替换子字符串给定一个字符串字典作为键和替换作为值。 Python
【发布时间】:2013-05-07 03:59:45
【问题描述】:

我有一本字典,其中 要替换的字符串keys,它的 replacement 为值。除了逐个令牌查看字符串之外,还有更好/更快的替换方法吗?

我一直这样做:

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}

sentence = "this is a foobar in a barbar withoutspace"

for i in sentence.split():
  if i in segmenter:
    sentence.replace(i, segmenter[i])

【问题讨论】:

  • 我刚才问过same question。那里有一些不错的答案。

标签: python string dictionary replace


【解决方案1】:

re.sub 可以调用返回替换的函数

segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
sentence = "this is a foobar in a barbar withoutspace"

import re

def fn(match):
    return segmenter[match.group()]

print re.sub('|'.join(re.escape(k) for k in segmenter), fn, sentence)

【讨论】:

  • +1 这比 split/get/join 方法更惯用和可控。一个要点:在构建这样的组合正则表达式时,请务必按键长度进行降序排序,以便像“without”这样的较长键不会被像“with”这样的较短键所掩盖。或者,使用“\b”来定位单词边界并防止键之间出现别名。
【解决方案2】:

字符串在 python 中是不可变的。因此,str.replace 返回一个新字符串,而不是修改原始字符串。您可以在此处使用str.join() 和列表理解:

>>> segmenter = {'foobar':'foo bar', 'withoutspace':'without space', 'barbar': 'bar bar'}
>>> sentence = "this is a foobar in a barbar withoutspace"

>>> " ".join( [ segmenter.get(word,word) for word in sentence.split()] )
'this is a foo bar in a bar bar without space'

str.replace 的另一个问题是它还会用

替换像 "abarbarb" 这样的词

"abar barb"

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2018-09-11
    • 2022-01-15
    • 2014-12-23
    • 2017-12-06
    相关资源
    最近更新 更多