从字符串中删除多个子字符串的最有效方法?

时间:2015-06-02 20:38:38

标签: python string performance

从字符串中删除子字符串列表的最有效方法是什么?

我想要一个更清洁,更快捷的方法来执行以下操作:

words = 'word1 word2 word3 word4, word5'
replace_list = ['word1', 'word3', 'word5']

def remove_multiple_strings(cur_string, replace_list):
  for cur_word in replace_list:
    cur_string = cur_string.replace(cur_word, '')
  return cur_string

remove_multiple_strings(words, replace_list)

1 个答案:

答案 0 :(得分:13)

正则表达式:

>>> import re
>>> re.sub(r'|'.join(map(re.escape, replace_list)), '', words)
' word2  word4, '

上述单行内容实际上没有string.replace版本快,但肯定更短:

>>> words = ' '.join([hashlib.sha1(str(random.random())).hexdigest()[:10] for _ in xrange(10000)])
>>> replace_list = words.split()[:1000]
>>> random.shuffle(replace_list)
>>> %timeit remove_multiple_strings(words, replace_list)
10 loops, best of 3: 49.4 ms per loop
>>> %timeit re.sub(r'|'.join(map(re.escape, replace_list)), '', words)
1 loops, best of 3: 623 ms per loop

天!快了近12倍。

但我们可以改善它吗?是。

由于我们只关注单词,我们可以做的只是使用words过滤掉\w+字符串中的单词,并将其与一组replace_list进行比较(是实际{ {1}}:set):

set(replace_list)

对于更大的字符串和单词,>>> def sub(m): return '' if m.group() in s else m.group() >>> %%timeit s = set(replace_list) re.sub(r'\w+', sub, words) ... 100 loops, best of 3: 7.8 ms per loop 方法和我的第一个解决方案将最终采用二次时间,但解决方案应该以线性时间运行。

相关问题