Skip to content Skip to sidebar Skip to footer

Key Substitution In Python

I have two text files, one we'll call keys and it looks something like this: S-84 S-72 S-73 S-83 32 S-73 S-83 32 S-65 32 S-84 S-69 S-83 S-84 S-49 The other file is sort of a dicti

Solution 1:

Yes, you must first read in the second file to create your dictionary.

import re

d['S-186'] = ':'  # To account for the delimiter per your comments below.
with open(key_values_filename, 'r') as f:
    for row in f:
        k, v = row.split(':')
        d[k.strip()] = re.sub('^"|"$', '', v.strip())

Then read the other file and get the value from the matched key.

missing_value = 'key missing'
with open(keys_filename, 'r') as fin, open(result_filename, 'w') as fout:
    for row in fin:
        fout.write(d.get(row.strip(), missing_value))

For an explanation of the regular expression re.sub('^"|"$', '', v.strip()), it removes double quotations found either at the start or end of each parsed string stripped of whitespace.

  • ^" asserts position of the quotation at the start of the string.
  • "$ asserts position of the quotation at the end of the string.
  • | matches either assertion above.

The above solution works on your sample data.


Solution 2:

You can try this:

import re

keys = {a:b for a, b in [re.split("\s:\s", i.strip('\n')) for i in open('second_file.txt')]}

final_message = ''.join(keys[i] for i in [b.strip('\n') for b in open('first_file.txt')])

Post a Comment for "Key Substitution In Python"