简体   繁体   中英

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?

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 ) 

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.

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

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;
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM