将字符串替换为字符串替换为键和替换为值替换子字符串。蟒蛇 [英] Replacing substrings given a dictionary of strings-to-be-replaced as keys and replacements as values. Python

查看:128
本文介绍了将字符串替换为字符串替换为键和替换为值替换子字符串。蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其中字符串要替换,其替换为值。除了通过令牌查看字符串令牌之外,是否有更好/更快的方式进行替换?

I have a dictionary with the strings to be replaced as keys and its replacement as values. Other than looking through the strings token by token, is there a better/faster way of doing the 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])


推荐答案

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

String are immutable in python. So, str.replace returns a new string instead of modifying the original string. You can use str.join() and list comprehension here:

>>> 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

Another problem with str.replace is that it'll also replace words like "abarbarb" with

abar barb

这篇关于将字符串替换为字符串替换为键和替换为值替换子字符串。蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆