Iterative find/replace from a list of tuples in Python

随声附和 提交于 2019-12-18 04:24:01

问题


I have a list of tuples, each containing a find/replace value that I would like to apply to a string. What would be the most efficient way to do so? I will be applying this iteratively, so performance is my biggest concern.

More concretely, what would the innards of processThis() look like?

x = 'find1, find2, find3'
y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')]

def processThis(str,lst):
     # Do something here
     return something

>>> processThis(x,y)
'replace1, replace2, replace3'

Thanks, all!


回答1:


You could consider using re.sub:

import re
REPLACEMENTS = dict([('find1', 'replace1'),
                     ('find2', 'replace2'),
                     ('find3', 'replace3')])

def replacer(m):
    return REPLACEMENTS[m.group(0)]

x = 'find1, find2, find3'
r = re.compile('|'.join(REPLACEMENTS.keys()))
print r.sub(replacer, x)



回答2:


A couple notes:

  1. The boilerplate argument about premature optimization, benchmarking, bottlenecks, 100 is small, etc.
  2. There are cases where the different solutions will return different results. if y = [('one', 'two'), ('two', 'three')] and x = 'one' then mhawke's solution gives you 'two' and Unknown's gives 'three'.
  3. Testing this out in a silly contrived example mhawke's solution was a tiny bit faster. It should be easy to try it with your data though.



回答3:


x = 'find1, find2, find3'
y = [('find1', 'replace1'), ('find2', 'replace2'), ('find3', 'replace3')]

def processThis(str,lst):
    for find, replace in lst:
        str = str.replace(find, replace)

    return str

>>> processThis(x,y)
'replace1, replace2, replace3'



回答4:


s = reduce(lambda x, repl: str.replace(x, *repl), lst, s)



回答5:


Same answer as mhawke, enclosed with method str_replace

def str_replace(data, search_n_replace_dict):
    import re
    REPLACEMENTS = search_n_replace_dict

    def replacer(m):
        return REPLACEMENTS[m.group(0)]

    r = re.compile('|'.join(REPLACEMENTS.keys()))
    return r.sub(replacer, data)

Then we can call this method with example as below

s = "abcd abcd efgh efgh;;;;;; lkmnkd kkkkk"
d = dict({ 'abcd' : 'aaaa', 'efgh' : 'eeee', 'mnkd' : 'mmmm' })


print (s)
print ("\n")
print(str_replace(s, d))

output :

abcd abcd efgh efgh;;;;;; lkmnkd kkkkk


aaaa aaaa eeee eeee;;;;;; lkmmmm kkkkk


来源:https://stackoverflow.com/questions/1175540/iterative-find-replace-from-a-list-of-tuples-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!