如何比较两个不同列中的数据无论是在不同的文本文件的顺序? [英] How to compare two different columns data regardless the order in different text files?

查看:196
本文介绍了如何比较两个不同列中的数据无论是在不同的文本文件的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要做到这一点,

输入1(文本文件1)

ABCD,  QI30  
FGDE,  Q140  
KLOM,  Q232   
..      ..  
..      ..   
..      ..

输入2(文本文件2)

Input2 (Text file 2)

DATA: ARRAY: KLOM: n: 000000000111111110011111111111111111111111  
DATA: ARRAY: ABCD: n: 000111111111111111101111111111111111111111  
DATA: ARRAY: FGDE: n: 010101010111111111111111111111111111111111  
..      ..  
..      ..   
..      ..

输出(在文本文件中写入3)

Output( write in text file 3)

Item=Q232; Var:KLOM    
read_Var:read_q232: Get_Data: n: 000000000111111110011111111111111111111111  

Item=Q130; Var:ABCD  
read_Var:read_q150: Get_Data: n: 000111111111111111101111111111111111111111  

Item=Q140; Var:FGDE  
read_Var:read_q170: Get_Data: n: 010101010111111111111111111111111111111111   
..      ..  
..      ..   
..      ..

这是code的一部分,

This is part of the code,

import collections

#Create a data dict using textfile1.txt
with open("textfile1.txt") as f1:   
    # create generator of entries using non-empty lines in file
    entries1 = (line.split() for line in f1 if line.strip())
    # create dict using ($1) as key and $2 as value
    data1 = dict(((d[0], d[1]) for d in entries1)

with open("textfile2.txt") as f2:   
    entries2 = (line.split() for line in f2 if line.strip())
    data2 = dict(((f[2], f[3]), f[4]) for f2 in entries2)

   set(d[1]) == set(f[2]) # compare the text file1 column 2 with text file2 column 3 

这一点后,我不知道该怎么做的已经。我真的需要你帮助的家伙。

After this point, I don't know how to do already. Really I need u guys help.

推荐答案

这产生所需的输出:

ids = {}
with open('input1.txt') as fobj:
    for line in fobj:
        if line.strip():
            key, value = [x.strip() for x in line.split(',')]
            ids[key] = value

arrays = []
with open('input2.txt') as fobj:
    for line in fobj:
        if line.strip():
            values = [x.strip() for x in line.split(':')]
            arrays.append((values[2], values[3:]))

with open('output.txt', 'w') as fobj:
    for key, values in arrays:
        item = ids[key]
        fobj.write('Item={}; Var:{}\n'.format(item, key))
        fobj.write('read_Var:read_{}: Get_Data: {}\n\n'.format(item.lower(),
                                                            ':'.join(values)))

这篇关于如何比较两个不同列中的数据无论是在不同的文本文件的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆