用同一单词的大小写搜索和替换单词

2024-05-20 22:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这个脚本的目的是替换多个字符串,不管这个单词是以小写字母还是大写字母开头。你知道吗

代码示例:

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中的任何单词),如果它是大写或小写的话。你知道吗


Tags: textimportreyoudefmatch单词dict
2条回答

用这样的附加参数编译正则表达式

<罢工>重新编译(“这里是正则表达式”,忽略案例)

编辑1:

好吧,结果是,由于双引号和单引号的用法不一致,您的replace\u dict的格式不正确。 以下是工作代码和预期输出:

鲍勃_芭蕾舞者你知道吗

import re

def word_replace(text, replace_dict):
    rc = re.compile(r"[A-Za-z_]\w*")

    def translate(match):
        word = match.group(0).lower()
        print(word)
        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",    # Everything is double quoted
    "debug" : "fix",
    "ship": "boat"
 }

output = word_replace(old_text, replace_dict)
print(output)

$ python bob_baller.py
bob baller: say why don't you play ball
jeff: i have no idea
bob baller: well maybe you should 

您可以将replace\u dict键转换为小写,然后匹配两个单词并替换。喜欢鲍勃和鲍勃的比赛。你知道吗

相关问题 更多 >