user1541722
user1541722

Reputation: 39

Python Replacing Words from Definitions in Text File

I've got an old informix database that was written for cobol. All the fields are in code so my SQL queries look like.

SELECT uu00012 FROM uu0001;

This is pretty hard to read.

I have a text file with the field definitions like

uu00012 client
uu00013 date
uu00014 f_name
uu00015 l_name

I would like to swap out the code for the more english name. Run a python script on it maybe and have a file with the english names saved.

What's the best way to do this?

Upvotes: 1

Views: 223

Answers (5)

mgilson
mgilson

Reputation: 309959

If each piece is definitely a separate word, re.sub is definitely the way to go here:

#create a mapping of old vars to new vars.
with open('definitions') as f:
    d = dict( [x.split() for x in f] )

def my_replace(match):
    #if the match is in the dictionary, replace it, otherwise, return the match unchanged.
    return d.get( match.group(), match.group() )

with open('inquiry') as f:
    for line in f:
        print re.sub( r'\w+', my_replace, line ) 

Upvotes: 1

bhawkfan
bhawkfan

Reputation: 11

import re

f = open("dictfile.txt")

d = {}
for mapping in f.readlines():
    l, r = mapping.split(" ")
    d[re.compile(l)] = r.strip("\n")

sql = open("orig.sql")
out = file("translated.sql", "w")

for line in sql.readlines():
    for r in d.keys():
        line = r.sub(d[r], line)
    out.write(line)

Upvotes: 0

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

dictionary = '''uu00012 client
uu00013 date
uu00014 f_name
uu00015 l_name'''

dictionary = dict(map(lambda x: (x[1], x[0]), [x.split() for x in dictionary.split('\n')]))

def process_sql(sql, d):
    for k, v in d.items():
        sql = sql.replace(k, v)
    return sql

sql = process_sql('SELECT f_name FROM client;', dictionary)

build dictionary:

{'date': 'uu00013', 'l_name': 'uu00015', 'f_name': 'uu00014', 'client': 'uu00012'}

then run thru your SQL and replace human readable values with coded stuff. The result is:

SELECT uu00014 FROM uu00012;

Upvotes: 0

Justin.Wood
Justin.Wood

Reputation: 715

infile = open('filename.txt','r')
namelist = []
for each in infile.readlines():
    namelist.append((each.split(' ')[0],each.split(' ')[1]))

this will give you a list of key,value pairs

i dont know what you want to do with the results from there though, you need to be more explicit

Upvotes: 0

Justin Jasmann
Justin Jasmann

Reputation: 2353

Conceptually,

I would probably first build a mapping of codings -> english (in memory or o.

Then, for each coding in your map, scan your file and replace with the codes mapped english equivalent.

Upvotes: 0

Related Questions