【发布时间】:2018-03-29 01:48:34
【问题描述】:
我刚刚开始使用 python (anaconda3),我无法弄清楚下面的问题 应该 真的很简单......我已经在互联网上搜索了一个解决方案,但我找不到。
目标:我希望我的脚本将输入文本文件中的各个列(通过 --column 索引)写入相应的输出文本文件。用户可以选择任意数量的列(具有匹配数量的输出文件)。
示例:python septc.py --infile infile.txt --column 0 2 3 --outfile out1.txt out2.txt out3.txt
我的问题:
- 如何在各个输出文件中保存由 --column 向量定义的输入文件的各个列?
- 当用户从 1 开始计数 col 而 python 从 0 开始计数时,用户给出的 col 的索引号可能会减少 1,因此选择最后一个 col 将超出范围...尽管我可以在帮助中说以 0 开头的脚本文件。
下面的脚本应该打印 infile 的第 1、第 3 和第 4 列,但它确实将所有 3 列写入每个输出文件,而不是将第 1 列写入 out1.txt,将第 3 列写入 out2。 txt,并将第 4 列放入 out3.txt。这是 bc 为外循环的每个实例执行内循环。同样,更改循环顺序会在每个输出文件中写入第 4 列,这不是我想要的。我尝试了其他方法(例如,for c in np.nditer(col))但无济于事。
我怀疑这种 for 循环方法在这里不合适。它应该类似于 for c in col 将 c 写入关联的文本文件...但是如何将 col 与其输出文件链接?!
非常感谢您的帮助!
非常感谢您,
网卡
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')
【问题讨论】:
标签: python arrays for-loop text-files nested-loops