I want to replace a very long string according to dictionary. My code is like that:
def rep(self, mystr, dict): new_pstr = '' for char in mystr: try: new_pstr += dict[char] except: continue return new_pstr This code is not as fast as I expected. Maybe without loop, it will be more faster. But I don't know how to do it. Last but not least, I can't replace all same character together, each time I should replace only one character. Therefore, replace function may not be my option. To be more clear, I give an example:
if d = {'A':'C', 'C':'B'} and mystr = 'AC', then the new_pstr = 'CB'
(If your way return me 'BB', which is not what I expected)
In actual case, my dictionary looks like that:
d = {u'q': [u'k'], u'v': [u'v'], u'e': [u'e'], u'\xe7': [u'\xe7'], u'\xe9': [u'e'], u'h': [u'y'], u'j': [u'z'], u'o': [u'u'], u'\xf1': [u'g'], u'i': [u'i'], u'\u015f': [u's'], u'\xf6': [u'u'], u'x': [u'x'], u'\xfc': [u'v'], u'\u011f': [u'g']} and my string like that:
str = "tériniñ yiriklişip kétişi havadiki nemlikniñ tövenlep ketkenlikidin bolup ، bu vaqitta tére téximu qurğaqlişip kétidu ، tériniñ ilastikiliqi acizlap ، xünük bolup qalidu. şuña xanim – qizlar bundaq vaqitta tére qurğaqlişişniñ aldini alidiğan çare– tedbirlerni qolliniş kérek. nemlikni saqlaşta yuquri dericilik su toluqlaş yüzlüki، hesel ve örük méğizi méyiğa muvapiq miqdarda un arilaşturup melhem qilip yüzge çaplap bers e، yaki nemxuşluqi yuquri bolğan tére nemleştürüş vazilin méyi sürüp berse، qurğaq térige su toluqlaşqa paydiliq." The reason I use try.. except ... because my code sometimes return error like that UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 2: ordinal not in range(128)
string.translate()?dictor other builtin types as variable names,mydictwould be more consistent withmystrexcept: continueis doing)