簡體   English   中英

從字符串中刪除多個子字符串的最有效方法?

[英]Most efficient way to remove multiple substrings from string?

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

我想要一個更清潔,更快捷的方法來做到以下幾點:

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)

正則表達式:

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

上面的單string.replace實際上沒有你的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倍。

但我們可以改進它嗎? 是。

因為我們只關心單詞,我們可以做的只是使用\\w+過濾words字符串中的words ,並將其與一組replace_list (是實際setset(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

對於更大的字符串和單詞, string.replace方法和我的第一個解決方案將最終采用二次時間,但解決方案應該以線性時間運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM