I have a .txt file with the following contents:
norway sweden bhargama bhargama forbisganj forbesganj canada usa ankara turkey
I want to rewrite the file so that it is its new contents:
'norway' : 'sweden', 'bhargama': 'bhargama', 'forbisganj' : 'forbesganj', 'canada': 'usa', 'ankara': 'turkey'
Basically, I want to turn a .txt file into a python dictionary so that I can manipulate it. Are there built-in libraries for this kind of task?
Here is my attempt:
import re target = open('file.txt', 'w') for line in target: target.write(re.sub(r'([az]+)', r'':'"\1"','', line))
I get quotes; but what correct regular expression does what I described above do?
source share