<p>这个脚本的目的是替换多个字符串,不管这个单词是以小写字母还是大写字母开头。你知道吗</p>
<p>代码示例:</p>
<pre><code>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'
}
</code></pre>
<p>我得到的是:</p>
<pre><code>bob baller: say why don't you play ball
jeff: i have no idea
bob: well maybe you should
</code></pre>
<p>我想从课文中得到的是“Bob”和“Bob”,然后用Bob baller替换它们。你知道吗</p>
<p>为了进一步澄清这个问题,我要做的是替换单词bob(或replaceèdict中的任何单词),如果它是大写或小写的话。你知道吗</p>