I have a .txt file with the following contents:
norway sweden
bhargama bhargama
forbisganj forbesganj
canada usa
ankara turkey
I want to overwrite the file such that these are its new contents:
'norway' : 'sweden',
'bhargama': 'bhargama',
'forbisganj' : 'forbesganj',
'canada': 'usa',
'ankara': 'turkey'
Basically I want to turn the .txt file into a python dictionary so I can manipulate it. Are there built in libraries for this sort of task?
Here is my attempt:
import re
target = open('file.txt', 'w')
for line in target:
target.write(re.sub(r'([a-z]+)', r'':'"\1"','', line))
I'm succeeding in getting the quotes; but what's the proper regex to do what I described above?
Sure. Just look them up as normal and check for matches. Note that re. match only produces a match if the expression is found at the beginning of the string.
regex = r"([a-zA-Z]+) (\d+)" if re.search(regex, "Jan 2"): match = re.search(regex, "Jan 2") # This will print [0, 5), since it matches at the beginning and end of the # string print("Match at index %s, %s" % (match.
Recompile is a term that refers to the act of compiling data or code again after the initial compilation. Below is an example of its use. "After I fixed the error in my code, I recompiled it." Compilers, like Eclipse and GCC, can recompile code.
sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string. To use this function, we need to import the re module first.
You don't need a regular expression for that.
File:
norway sweden
bhargama bhargama
forbisganj forbesganj
canada usa
ankara turkey
Code:
with open('myfile.txt') as f:
my_dictionary = dict(line.split() for line in f)
This goes through each line in your file and splits it on whitespace into a list
. This generator of list
s is fed to dict()
, which makes each one a dictionary key and value.
>>> my_dictionary['norway']
'sweden'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With