简体   繁体   English

如何在Python中合并来自不同txt文件的一些列数据?

[英]how to merge some columns data from different txt files in Python?

I have some txt files, which need to extract certain columns out and store in one txt file. 我有一些txt文件,需要提取某些列并存储在一个txt文件中。

a1.txt: a1.txt:

53, 42 53,42
54, 38 54,38
55, 37 55,37
57, 48 57,48

b1.txt: b1.txt:

45, 15, 30, 2 45,15,30,2
16, 59, 31, 4 16,59,31,4
87, 09, 32, 5 87,09,32,5
58, 16, 33, 3 58,16,33,3

what i need is c.txt (add the last column of b1.txt to the a1.txt): 我需要的是c.txt(将b1.txt的最后一列添加到a1.txt):

53, 42, 2 53,42,2
54, 38, 4 54,38,4
55, 37, 5 55,37,5
57, 48, 3 57,48,3

the 4th column of b.txt should be added to the 5th column of a.txt . b.txt的第4列应添加到a.txt的第5列。 Then create a new file c.txt . 然后创建一个新文件c.txt I try some code, but it did not work. 我尝试了一些代码,但它没有用。 cmd said "TypeError: list indice must be integers, not srt" . cmd说"TypeError: list indice must be integers, not srt" I have no idea how to merge the columns from different files together. 我不知道如何将不同文件中的列合并在一起。 Hopefully someone could help me to revise the code. 希望有人可以帮我修改代码。 Thank you so much! 非常感谢!

def readf(filename):
    lines=file(filename).readlines()
    for i in lines:
        data=i.split()
    return data

fa=readf('a1.txt')
fb=readf('b1.txt')

lines=[]
for i in fa:
    s=fa[i]+fb[3]
    s+='\n'
    lines.append(s)

with open ('c.txt','w') as f:
    f.writelines(lines)
    f.close>

In the following command you have passed a string as the index to a list : 在以下命令中,您已将字符串作为索引传递给列表:

for i in fa:
    s=fa[i]+fb[3]

Note that you are iterating over a file object! 请注意 ,您正在迭代文件对象!

but as a better way for such problems i suggest the csv module. 但作为解决此类问题的更好方法,我建议使用csv模块。

from itertools import izip_longest
import csv
with open('a1.txt', 'rb') as csv1,open('b1.txt', 'rb') as csv2,open('c.txt', 'w') as out:
     spam1 = csv.reader(csv1, delimiter=',')
     spam2 = csv.reader(csv2, delimiter=',')
     last_column=list(izip_longest(*spam2))[-1]
     for i,j in  izip_longest(spam1,last_column):
        out.write(','.join([t.strip(';') for t in i])+','+j+'\n')

Here last_column=list(izip_longest(*spam2))[-1] will gave you the last column of b1.txt and izip_longest(spam1,last_column) will gave you the following list : 这里last_column=list(izip_longest(*spam2))[-1]将为您提供b1.txt的最后一列, izip_longest(spam1,last_column)将为您提供以下列表:

[(['53', ' 42;'], ' 2;'), (['54', ' 38;'], ' 4;'), (['55', ' 37;'], ' 5;'), (['57', ' 48; '], ' 3;')]

So you can strip the elements with ; 所以你可以剥掉元素; and write to file. 并写入文件。

If ; 如果; can be ignored you can change the last line to : 可以忽略你可以将最后一行更改为:

out.write(','.join(i)+','+j+'\n')

Since you need to split your text using , and ; 由于需要使用分割你的文字,; as parameters, you can use re to accomplish the job. 作为参数,您可以使用re来完成工作。 Then is just a matter or writing all the attributes of the first file and the last attribute of the second file. 然后只是一个问题或写入第一个文件的所有属性和第二个文件的最后一个属性。

import re
with open("a.txt", 'r') as f:
    a1 = [re.findall(r"[\w']+", line) for line in f]
with open("b.txt", 'r') as b:
    b1 = [re.findall(r"[\w']+", line) for line in b]
with open("c.txt", 'w') as c:
    for x,y in zip(a1,b1):
        c.write("{},{}\n".format(",".join(x),y[-1]))  

This creates file c which looks like 这会创建看起来像的文件c

53,42,2 
54,38,4 
55,37,5 
57,48,3

How about you use pandas: 你用大熊猫怎么样:

import pandas as pd
a1 = pd.read_csv('a1.txt', header= None ,escapechar=';')
b1 = pd.read_csv('b1.txt', header= None)

a1[2] = b1[3]

a1.to_csv('c.txt',index=False,header= False)

c.txt: c.txt:

53, 42, 2;
54, 38, 4;
55, 37, 5;
57, 48, 3;
def read_file(file_name):
    col_data = []
    with open(file_name) as data_file:
        for data in data_file.readlines():
            col1, col2, col3, col4 = data.split(",")
            col_data.append(col4[:-1])
    return col_data

numbers = read_file("b1.txt")

with open("a1.txt") as a_file:
    with open("new_file.txt", "w") as new_file:
        lines = a_file.readlines()
        for line in xrange(len(lines)):
            new_file.write(lines[line][:-1] + " ,"+numbers[line]+"\n")

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM