【发布时间】:2018-09-25 12:33:12
【问题描述】:
此脚本的重点是替换多个单词字符串,无论单词以小写字母还是大写字母开头。
代码示例:
import re
from re import sub
def word_replace(text, replace_dict):
rc = re.compile(r"[A-Za-z_]\w*")
def translate(match):
word = match.group(0)
return replace_dict.get(word, word)
return rc.sub(translate, text)
old_text = """Bob: say why don't you play ball
jeff: i have no idea
bob: well maybe you should """
replace_dict = {
"Bob" : 'bob baller',
"debug" : "fix",
'ship': 'boat'
}
我得到的是:
bob baller: say why don't you play ball
jeff: i have no idea
bob: well maybe you should
我想从文本中得到“Bob”和“bob”,然后将它们都替换为 bob Baller。
为了进一步澄清这个问题,我要做的是替换单词“bob”(或replace_dict中的任何单词),如果它是大写或小写的。
【问题讨论】:
标签: python python-3.x replace