Case insensitive dictionary

后端 未结 10 2420
栀梦
栀梦 2020-11-27 14:47

I\'d like my dictionary to be case insensitive.

I have this example code:

text = \"practice changing the color\"

words = {\'color\': \'colour\',
            


        
10条回答
  •  难免孤独
    2020-11-27 15:20

    While a case insensitive dictionary is a solution, and there are answers to how to achieve that, there is a possibly easier way in this case. A case insensitive search is sufficient:

    import re
    
    text = "Practice changing the Color"
    words = {'color': 'colour', 'practice': 'practise'}
    
    def replace(words,text):
            keys = words.keys()
            for i in keys:
                    exp = re.compile(i, re.I)
                    text = re.sub(exp, words[i], text)
            return text
    
    text = replace(words,text)
    print text
    

提交回复
热议问题