亲爱的所有)我有一个问题,这对我来说是相当困难的,因为我刚刚开始做Python。因此,让我们想象一下,我们有一个2列文件,如:
col_1 col_2
1 6
2 7
3 8
4 9
5 10
我需要执行几个转换(使用不同的方程),这将创建额外的列(基本上,大约15列)。但我不知道如何将其包装为可读的和逻辑的代码。
让我向你展示我的想法(我确信它们是非常错误的,但我真的希望你的眼睛不会流血:)。首先,在这个问题上使用类是一个合适的想法吗?还是只做些功能?
INPUT = 'input.txt'
OUTPUT = 'output.txt'
def col_3_function():
with open(INPUT, 'r') as reader, open(OUTPUT, 'a') as writer:
for line in reader:
global col_3
column = line.strip().split()
col_1 = float(column[1])
col_2 = float(column[2])
col_3 = (col_1 + col_2)
def col_4_function():
with open(INPUT, 'r') as reader, open(OUTPUT, 'a') as writer:
for line in reader:
global col_4
column = line.strip().split()
col_1 = float(column[1])
col_2 = float(column[2])
col_4 = col_3 - col_2
print(col_1, col_2, col_3, col_4, sep='\t', file=writer)
if __name__ == '__main__':
col_4_function()
以此类推,直到有必要数量的列。
对我来说有几个绊脚石:
对我来说还有很多困难,但我应该从最一般的开始。
我知道这是一个非常普遍和大的问题,但这对我来说是非常重要的。我真的很感谢你的想法和想法。真的。
发布于 2015-10-08 13:09:45
这是一个基本的方法。它不处理文件中的第一行(我不知道您想如何命名列,所以我没有这样做:)
INPUT = "toto.txt"
OUTPUT = "titi.txt"
def col3_fn(columns):
""" Just sum column 1 and 2. Used as generator of column 3 content """
return int(columns[0]) + int(columns[1])
def col4_fn(columns):
""" Difference between column 2 and 3. Used as generator of column 4 content """
return int(columns[1]) - int(columns[2])
# List of functions used for column generation.
# You can add as much as you want.
functions = [col3_fn, col4_fn]
with open(INPUT, "r") as inp, open(OUTPUT, "w") as out:
for line in inp.readlines():
splited = line[:-1].split()
for f in functions:
splited.append(str(f(splited)))
out.write("\t".join(splited) + "\n")
输入文件(toto.txt):
1 1
2 2
3 3
输出文件(titi.txt):
1 1 2 -1
2 2 4 -2
3 3 6 -3
发布于 2015-10-08 14:18:55
你应该用numpy
import numpy as np
col1, col2 = np.loadtxt (INPUT, dtype=int, unpack=True)
col3 = col1 + col2
col4 = col3 - col2
np.savetxt (OUTPUT, np.vstack((col1, col2, col3, col4)).T, fmt='%d')
如果您在浮动上操作,则不需要dtype
和fmt
参数
https://stackoverflow.com/questions/33016495
复制相似问题