can you write a str.replace() using dictionary values in Python?

后端 未结 10 864
小鲜肉
小鲜肉 2020-12-03 00:20

I have to replace the north, south, etc with N S in address fields.

If I have

list = {\'NORTH\':\'N\',\'SOUTH\':\'S\',\'EAST\':\'E\',\'WEST\':\'W\'}         


        
10条回答
  •  情话喂你
    2020-12-03 01:07

    I would suggest to use a regular expression instead of a simple replace. With a replace you have the risk that subparts of words are replaced which is maybe not what you want.

    import json
    import re
    
    with open('filePath.txt') as f:
       data = f.read()
    
    with open('filePath.json') as f:
       glossar = json.load(f)
    
    for word, initial in glossar.items():
       data = re.sub(r'\b' + word + r'\b', initial, data)
    
    print(data)
    

提交回复
热议问题