簡體   English   中英

如何使用Python或bash將兩列數組中的數字替換為另一個文件中的相應字符串?

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

我有兩個文件,1個包含兩列數字

文件1:

1  3

2  3

2  1

34 2

...

檔案2:

1   CA1

2   CB1

3   CC1

34   DD1

...

因此,我希望我的輸出文件看起來像這樣

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')

並檢查file3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM