首页 > 解决方案 > 大字符串中多次替换的有效方法

问题描述

我想在一个字符串中迭代地加入多组字符。例子:

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 nen中,然后加入en tent等等。连接按顺序完成很重要,因为连接 ('en', 't') 不起作用,除非 ('e', 'n') 已连接。

对于 20MB 和 10k 连接的字符串,这需要一段时间。我正在寻找优化这个,但我不知道如何。我丢弃的一些东西:

是否有任何算法、字符串或正则表达式或任何其他函数可以让我这样做?谢谢!

标签: pythonstring

解决方案


直接的方法是:

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)

您必须对这两种方法进行基准测试。


推荐阅读