Function needs to change each word but changes each character

I've got this piece of code

dict1={'h':['H'], 'e':['E'], 'l':['LL'], 'o':['O'], 'hello':['HELLO']}

def replfunc(match):     
    return dict1[match.group(0)] 
regex = re.compile('|'.join(re.escape(x) for x in dict1)) 
with open('/old.txt') as fin, open('/new.txt','w', encoding='UTF-8') as fout:     
   for line in fin:         
    fout.write(regex.sub(replfunc,line))

This piece of code currently reads in the old text file and matches characters in this file with dict1 and outputs the new value in the new text file. I would like the above function to match words instead of characters how would i go about altering this? For example if my old text file had the word 'hello' in it the output currently is 'HELLLLO' as it reads in characters but i would like the function to read that the word 'hello' is a key in the dictionary and print out 'HELLO'

How would I go about doing this?



from Recent Questions - Stack Overflow https://ift.tt/3nkXJzW
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Network Error and Timeout on Authorize.net JS

Spring Elasticsearch Operations