Riska Nanda Riska Nanda - 3 months ago 9
Python Question

Converting value to key from dictionary

I have a txt file with the following text:

a = 1
b = 2
c = 3
d = 4
f = 5
etc.


and I have another file with the following text:

adfac
fdcba
etc.


I want to output into:

adfac = 1,4,5,1,3
fdcba = 5,4,3,2,1


This is what I have so far:

import nltk
f = open(r'C:\folder\dic\file.txt','r')
answer = {}
for line in f:
k, v = line.strip().split('=')
answer[k.strip()] = v.strip()

f.close()

print answer.values()

h = open(r'C:\folder\dic\file2.txt','r')
raw=h.read()
tokens = nltk.sent_tokenize(raw)
text = nltk.Text(tokens)


for line in text:
word = line
for value in answer.values():
if value == word:
word=answer[keys]
else:
word="not found"

print word


What would be the best way to do this in Python?

Answer

Please check this code.

f = open(r'C:\Users\dinesh_pundkar\Desktop\val.txt','r')
val_dict = {}
for line in f:
     k, v = line.strip().split('=')
     val_dict[k.strip()] = v.strip()
f.close()

print val_dict
#{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6','z':'26'}

h = open(r'C:\Users\dinesh_pundkar\Desktop\str_txt.txt','r')
str_list = []
for line in h:
     str_list.append(str(line).strip())

print str_list
#['adfac', 'fdcba', 'aadc', 'abcdef','zzzza']   

tmp_str = ''
for val in str_list:
    tmp_str = val 
    for k in val_dict.keys():
            if k in val:
                replace_str = str(val_dict[k]).strip() + ","
                tmp_str = tmp_str.replace(k,replace_str)

    tmp_str = tmp_str.strip(",")
    print val, " = ", tmp_str
    tmp_str = ''

Output :

C:\Users\dinesh_pundkar\Desktop>python demo.py
{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6', 'z': '26'}
['adfac', 'fdcba', 'aadc', 'abcdef', 'zzzza']
adfac  =  1,4,6,1,3
fdcba  =  6,4,3,2,1
aadc  =  1,1,4,3
abcdef  =  1,2,3,4,5,6
zzzza  =  26,26,26,26,1

Please let me know if this helps.