I have a string that need to be replaced.
myString = 'I have a cat, it like food'
I want to replace 'cat' with 'dog', or if there's 'dog' in the string, then replace 'dog' with 'cat'.
meanwhile, I need to replace 'like' with 'love', or 'love' with 'like'.
use OrderedDict can set the conditions' order, but it will skip the rest of the condition if one condition meet
from collections import OrderedDict
def replace_all(text, dic):
for i, j in dic.items():
text = text.replace(i, j)
return text
od = OrderedDict([("cat", "dog"), ("dog", "cat"), ("like ", "love"), ("love", "like")])
myString = "I have a cat, it like food"
replace_all(myString, od)
print(myString)
please advice.
this is another way of doing it
import re
od = OrderedDict([("cat", "dog"), ("dog", "cat"), ("like", "love"), ("love", "like")])
string = "I have a cat, it like food"
for word in re.split(", | ", string):
if word in od:
string = string.replace(word, od[word])
Yet a straight forward lambda hash replacement
>>> import re
>>>
>>> negations_dic = {"cat":"dog", "dog":"cat", "like":"love", "love":"like"}
>>> neg_pattern = re.compile(r'(?:cat|dog|like|love)')
>>>
>>> def negate_all(text):
... return neg_pattern.sub(lambda m: negations_dic[m.group()], text)
...
>>> print ( negate_all("I have a cat, it like food") )
I have a dog, it love food
Use re.sub
with lambda func in replacement part. Since the replacement occurs upon every inline match, there won't be any duplicate replacements.
>>> r = [("cat", "dog"), ("dog", "cat"), ("like", "love"), ("love", "like")]
>>> dict(r)
{'like': 'love', 'cat': 'dog', 'love': 'like', 'dog': 'cat'}
>>> d = dict(r)
>>> re.sub(r'\b(?:' + '|'.join(d.keys()) + r')\b', lambda x: d[x.group()], s)
'I have a dog, it love food'
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.