简体   繁体   中英

How to substitute numbers in a two column array with corresponding strings in another file using Python or bash?

I have two files, 1 contains a two column array of numbers

File 1:

1  3

2  3

2  1

34 2

...

File 2:

1   CA1

2   CB1

3   CC1

34   DD1

...

Therefore I would like my output file to look like this

CA1 CC1

CB1 CC1

CC1 CA1

DD1 CB1
# Here is another approach  
name = dict()
with open('file2', 'r') as f:
    lines = f.readlines()

for line in lines:
    col = line.split()
    name[col[0]] = col[1]

with open('file1', 'r') as f:
    lines = f.readlines()

for line in lines:
    col = line.split()
    print('{} {}'.format(name[col[0]], name[col[1]]))
>>> with open('file2') as f:
...     values = [i.strip() for i in f if i.strip() != '']

>>> d = dict([i.split() for i in values])

>>> with open('file1') as f:
...     keys = [i.strip() for i in f if i.strip() != '']

>>> with open('file3', 'w') as f:
...     for i, j in [i.split() for i in keys]:
...         f.write(d[i]+' '+d[j]+'\n')

And check the file3 .

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