Key substitution in python -


i have 2 text files, 1 we'll call keys , looks 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 sort of dictionary of key-value pairs:

s-49 : "!" s-65 : "a" s-66 : "b" s-67 : "c" s-68 : "d" s-69 : "e" s-70 : "f" s-71 : "g" s-72 : "h" s-73 : "i" s-74 : "j" s-75 : "k" s-76 : "l" s-77 : "m" s-78 : "n" s-79 : "o" s-80 : "p" s-81 : "q" s-82 : "r" s-83 : "s" s-84 : "t" s-85 : "u" s-86 : "v" s-87 : "w" s-88 : "x" s-89 : "y" s-90 : "z" 32 : " " 

i want read in first file , replace keys therein values in second file output file looks this:

this test! 

i don't know start this. trying start manually, output bleh

with open('newkey.log', 'r') input_file, open('newkey.txt', 'w') output_file:     line in input_file:         if line.strip() == 's-84':             output_file.write('t\n')         else:             output_file.write('bleh\n') 

i think going have read-in second file dictionary well, or hard-code in? prefer end being able change file outside of interpreter.

yes, must first read in second file create dictionary.

import re  d['s-186'] = ':'  # account delimiter per comments below. open(key_values_filename, 'r') f:     row in f:         k, v = row.split(':')         d[k.strip()] = re.sub('^"|"$', '', v.strip()) 

then read other file , value matched key.

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

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

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

the above solution works on sample data.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -