代码之家  ›  专栏  ›  技术社区  ›  nic

如何在python中将输入文本文件中的各个列保存到各个输出文本文件

  •  0
  • nic  · 技术社区  · 6 年前

    我刚刚开始使用python(anaconda3),我不知道下面的问题是什么 应该 真的很简单。。。我在互联网上到处寻找解决方案,但找不到。

    目标: 我希望脚本将输入文本文件中的各个列(通过--column索引)写入各自的输出文本文件。用户可以选择任意数量的列(具有匹配数量的输出文件)。

    示例:python septc。py—填充填充。txt—列0 2 3—输出文件out1。txt输出2。txt输出3。txt文件

    我的问题:

    1. 如何在各个输出文件中保存由--列向量定义的输入文件的各个列?
    2. 用户给出的列的索引数可能会减少1,因为用户从1开始计算列,而python从0开始计算列,所以选择最后一个列是不允许的。。。虽然我可以在脚本的帮助文件中说,计数从0开始。

    下面的脚本应该打印infle的第1、3和4t列,但它会将所有三列写入每个输出文件,而不是将第1列写入out1。txt,第三列输入out2。txt和out3的第4列。txt。这是bc,内部循环针对外部循环的每个实例执行。类似地,更改循环顺序会在每个输出文件中写入第4列,这不是我想要的。我尝试过其他方法(例如,对于np.nditer(col)中的c),但没有任何效果。

    我怀疑这种for-loop方法在这里不合适。它应该类似于c列中的c将c写入关联的文本文件。。。但如何将列与其输出文件链接?!

    我真的很感激你的帮助!

    提前非常感谢您,

    Nic

    cols = [0,2,3]
    data = np.arange(20).reshape(5,4)
    np.savetxt('infile.txt', data, delimiter='  ', fmt='%1.0f')
    f = np.loadtxt('infile.txt')
    array([[  0.,   1.,   2.,   3.],
           [  4.,   5.,   6.,   7.],
           [  8.,   9.,  10.,  11.],
           [ 12.,  13.,  14.,  15.],
           [ 16.,  17.,  18.,  19.]])
    
    ######### Script (shorter version) #########
    #!/usr/bin/env python
    import numpy as np
    import sys
    import argparse
    # Parse cmd line arguments
    p = argparse.ArgumentParser()
    p.add_argument('--infile', nargs='?', action="store", default=sys.stdin)
    p.add_argument('--column', nargs='+', action="store", type=int)
    p.add_argument('--outfile', nargs='+', action="store", default=sys.stdout)
    nargs = p.parse_args()
    # Assign cmd line arguments to variables
    col = nargs.column
    outfile = nargs.outfile
    infile = nargs.infile
    with open(infile) as infile:
        data = np.loadtxt(infile)
    # This is supposed to save each col into its respective output file ... supposed to ...
    for out in outfile:
        with open(out, 'wb') as f:
            for c in col:
                y = data[:,c]
                np.savetxt(f, y, fmt='%1.0f')
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Anil_M    6 年前

    您正在迭代每个输出文件的所有列。试着在立柱和外桩之间建立一种关系,比如使用 zip 。然后只需将各个列的文本保存到相应的文件中。

    有关内置函数的详细信息 拉链 here

    for out, c in zip(outfile,col):
        with open(out, 'wb') as f:
            y = data[:,c]            
            np.savetxt(f, y, fmt='%1.0f')
    

    希望这有帮助。

    结果:

    $ python col2files.py  --infile infile.txt --column 0 2 3 --outfile out1.txt out2.txt out3.txt
    
    $ cat out1.txt
    0
    4
    8
    12
    16
    
    $ cat out2.txt
    2
    6
    10
    14
    18
    
    $ cat out3.txt
    3
    7
    11
    15
    19