python 同时replace多个字符串/批量替换 的方法

前言

希望有这么一个replaceMuti函数能实现:

text = "Nice to meet you!"
olds = ["e", "t"]
news = ["t", "e"]
result = replaceMulti(text, olds, news)
print(result)

输出

Nict eo mtte you!

而不是这样的情况 ① ^①

Nice to meee you!

只用replace连续替换可以实现吗?

并不能,只用replace连续替换会出现 ① 的情况。因为多个单词的替换并不是同一次进行的,所以上次替换后的文本会在下次被替换。比如想把 “2333” 的 “2” 换成 “3”,“3” 换成 “2”,连续replace会怎么样?第一次replace后变成 “3333”,第二次replace后变成 “2222”。

实现同时replace多个单词的方法

思路(以"Nice to meet you!"为例)

  1. 把要替换的单词先替换为【中间变量】
    1. 设计中间变量的形式:< n >(n是单词的序号)
    2. 对 e 替换,替换后,text变成 “Nic<1> to m<1><1>t you!”
    3. 再用此法对 t 替换,text变成 “Nic<1> to m<1><1><2> you!”
  2. 把【中间变量】替换为目标单词
    1. 把<1>替换为 t
    2. 把<2>替换为 e

缺点及改善方法

缺点

要替换的字符串(目标单词)不能是【中间变量】中的任意一个字符。
以< m >来说,><部分数字 都不能作为要替换的字符串。

改善方法

对【中间变量】构造正则表达式。替换符合表达式的内容。
PS:具体方法尚未得出。作者是python初学者,尚未掌握正则用法。

函数代码

def replaceFomat(text: str, word: str, n: int,reverse=False):
    '''对文本中的指定单词进行格式化的替换/替回
    Params:
    ---
    text
        要替换的文本
    word
        目标单词
    n
        目标单词的序号
    reverse
        是否进行替回
    Return:
    ---
    new_text
        替换后的文本
    '''
    # 构造【中间变量】
    new_text = text[ : ]
    fmt = "<{}>".format(n)
    # 替换
    if reverse is False:
        new_text = new_text.replace(word, fmt)  # 格式化替换
        return new_text
    # 替回
    elif reverse is True:
        new_text = new_text.replace(fmt, word)  # 去格式化替换
        return new_text
    # 要求非法,引发异常
    else:
        raise TypeError

def replaceMulti(text: str, olds: list, news: list):
    '''一次替换多组字符串
    Params:
    ---
    text
        要替换的文本
    olds
        旧字符串列表
    news
        新字符串列表
    Return:
    ---
    new_text: str
        替换后的文本
    '''
    if len(olds) != len(news):
        raise IndexError
    else:
        new_text = text[ : ]
        # 格式化替换
        i = 0  # 单词计数器
        for word in olds:
            i += 1
            new_text = replaceFomat(new_text, word, i)
        # 去格式化替回
        i = 0  # 归零
        for word in news:
            i += 1
            new_text = replaceFomat(new_text, word, i,True)
        # 返回替换好的文本
        return new_text

效果测试

def test():
    text = "Nice to meet you!"
    olds = ["e", "t"]
    news = ["t", "e"]
    result = replaceMulti(text, olds, news)
    print(result)

def test2():
    text = "aabbb  abb  aaab  ab"
    olds = ["a", "b"]
    news = ["b", "a"]
    result = replaceMulti(text, olds, news)
    print(result)

test()
test2()

输出

Nict eo mtte you!
bbaaa  baa  bbba  ba

写在最后

python初学者,如有错误,欢迎指出。同时希望你能给出更好的实现方法,或者是使用正则表达式的改善方法,谢谢。

  • 8
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值