0

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

我一直在这样做:

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])
4

2 回答 2

5

字符串在 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".

于 2013-05-13T07:16:30.883 回答
4

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)
于 2013-05-13T07:32:04.060 回答