简体   繁体   English

如何使用Python或bash将两列数组中的数字替换为另一个文件中的相应字符串?

[英]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 我有两个文件,1个包含两列数字

File 1: 文件1:

1  3

2  3

2  1

34 2

...

File 2: 档案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 . 并检查file3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何用 python 中的列表字符串替换 numpy 数组的数字 - How to substitute numbers of a numpy array with strings of a list in python 如何使用python用列表中的几个数字替换文本文件中的字符串? - How to substitute string in a text file with a couple of numbers in a list using python? 使用Python和NLP,如何从Excel列中包含大量自由文本的字符串中提取某些文本字符串和相应的数字? - Using Python & NLP, how can I extract certain text strings & corresponding numbers preceding the strings from Excel column having a lot of free text? 如何有效地将充满 14 位二进制数的 numpy.array 转换为 python 中相应的二进制补码? - how to efficiently convert numpy.array full of 14 bit binary numbers into corresponding two's complement in python? 如何将带有多个字符串的python数组保存到人类可读的文件中 - How to save a python array with numbers of strings to a file that is human readable 在另一列的数组 python/pyspark 中创建两个相邻数字之间的差异数组列 - Create column of array of differences between two adjacent numbers in another column's array python/pyspark 使用 python 根据另一列中的相应值对列中的小数进行四舍五入 - Using python to round decimals in a column based on the corresponding value in another column 需要在另一个文件中查找行模式并使用 python 获取特定列中相应值的总和 - Needs to find line pattern in another file and get the sum of corresponding value in particular column using python 如何使用python将数组内的字符串切成另一个数组 - how to slice strings inside array into another array using python 如何用数字和字符串连接 python 中的两个列表? - how to concatenate two lists in python with numbers and strings?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM