文章目录
前言
只用replace连续替换可以实现吗?
实现同时replace多个单词的方法
思路(以"Nice to meet you!"为例)
缺点及改善方法
缺点
改善方法
函数代码
效果测试
写在最后
前言
希望有这么一个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!"为例)
把要替换的单词先替换为【中间变量】
设计中间变量的形式:< n >(n是单词的序号)
对 e 替换,替换后,text变成 “Nic<1> to m<1><1>t you!”
再用此法对 t 替换,text变成 “Nic<1> to m<1><1><2> you!”
把【中间变量】替换为目标单词
把<1>替换为 t
把<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初学者,如有错误,欢迎指出。同时希望你能给出更好的实现方法,或者是使用正则表达式的改善方法,谢谢。