Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: regex to make a python dictionary out of a sequence of words?

Tags:

python

regex

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?

like image 385
ifma Avatar asked Oct 19 '15 05:10

ifma


People also ask

Can you use regex in dictionary python?

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.

How do you perform pattern matching in python explain?

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.

What is re compile?

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.

WHAT IS RE sub in Python?

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.


1 Answers

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 lists is fed to dict(), which makes each one a dictionary key and value.

>>> my_dictionary['norway']
'sweden'
like image 118
TigerhawkT3 Avatar answered Oct 05 '22 23:10

TigerhawkT3