How to replace the values with keys ?

Graps Graps wegraps at gmail.com
Wed Jul 23 00:30:43 EDT 2008


Hi all,

I am a newbie to python... I have two text files text1 and text2. Text1 is a
tabbed separated file, say like

a b
a c
a d
a g
b c
b d
b h
c d
c h... and so on..

Text2 is a python dictionary containing data as

{0: 'a', 1: 'b', 2: 'c'...}

now I want the data in text1 to be replaced with the keys, say like

0 1
0 2
0 3
0 6
1 2... so on..
Is there some way I could do it in python?

I tried

import aDict
import re
infile = open('text1.txt','rw')
outfile = open('text3.txt','w')
def replace_words(infile, aDict):
    rc=re.compile('|'.join(map(re.escape, aDict)))
    def translate(match):
         return aDict[match.group(0)]
         return rc.sub(translate, infile)
outfile = replace_words(infile,aDict)

I am thrown with:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in replace_words
TypeError: argument 2 to map() must support iteration

I imported text2.txt , containing python dictionary as aDict.py. I want the
replaced values in a separate file text3.txt.


Thanking in advance..,
GraPs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080723/a1c54580/attachment.html>


More information about the Python-list mailing list