python - 大字符串中多次替换的有效方法
问题描述
我想在一个字符串中迭代地加入多组字符。例子:
mystr = 'T h i s _ i s _ a _ s e n t e n c e'
joins = [('e', 'n'), ('en', 't'), ('i', 's'), ('h', 'is')]
# do multiple replace
for bigram in joins:
mystr = mystr.replace(' '.join(bigram), ''.join(bigram))
print(mystr)
'T his _ is _ a _ s ent en c e'
在第一次迭代中,它加入e n
到en
中,然后加入en t
到ent
等等。连接按顺序完成很重要,因为连接 ('en', 't') 不起作用,除非 ('e', 'n') 已连接。
对于 20MB 和 10k 连接的字符串,这需要一段时间。我正在寻找优化这个,但我不知道如何。我丢弃的一些东西:
- 我没有像在这个问题中那样使用正则表达式,因为我不知道如何
re.sub
在替换是匹配本身但连接在一起的地方做 - 我也没有使用
str.translate
like this question,因为据我所知,翻译只能翻译单个字符,而在我joins
有多个
是否有任何算法、字符串或正则表达式或任何其他函数可以让我这样做?谢谢!
解决方案
直接的方法是:
mystr = 'T h i s _ i s _ a _ s e n t e n c e'
bigrams = [('e', 'n'), ('en', 't'), ('i', 's'), ('h', 'is')]
for first_part, second_part in bigrams:
mystr = mystr.replace(first_part + ' ' + second_part, first_part + second_part)
print(mystr)
印刷:
T his _ is _ a _ s ent en c e
第二种方式:
mystr = 'T h i s _ i s _ a _ s e n t e n c e'
bigrams = [('e', 'n'), ('en', 't'), ('i', 's'), ('h', 'is')]
for bigram in bigrams:
mystr = mystr.replace(' '.join(bigram), ''.join(bigram))
print(mystr)
您必须对这两种方法进行基准测试。
推荐阅读
- java - 一种递归方法和一种迭代方法的空堆栈
- android - 拦截 NavigationUI.onNavDestinationSelected() 以使用“inclusive = true”使 backstack 弹出
- c - 蓝牙通信延迟大
- mysql - Mysql - 如何合并两个不重复的 json 字符串数组?
- php - PHP datediff 过日问题
- elasticsearch - 未根据 ES 查询中传递的大小参数进行聚合
- javascript - 没有窗口的窗口属性
- matlab - 如果语句中的 X=0 的值未在 matlab 图中绘制
- azure - Azure ARM 部署 - 多个订阅
- android - Android Studio 中的多个根标签错误(清单 - 问题
)