繁体   English   中英

Python-将2列文件转换为10列

[英]Python - Convert a 2-column file into 10-column

亲爱的所有人)我遇到了一个很难解决的问题,因为我刚开始使用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()

依此类推,直到有必要的列数为止。

我有两个绊脚石:

  • 即使在此简单版本中也不起作用:)
  • 据我所知,使用很多全局变量是一种动静。
  • 接下来的每一列均应使用数据,而不仅应使用列1和2中的数据,还应使用先前在column_3,column_4等中创建的数据。
  • 我也不喜欢每个功能的重复性。 不是Python方法。
  • 我应该上课吗? 还是只是功能? 应该是什么样?

对我来说,还有许多其他困难,但我应该从最一般的角度开始。

我知道这是一个相当普遍的大问题,但这对我来说非常重要。 我真的很感谢您的想法和想法。 真。

这是一个基本方法。 它不处理文件的第一行(我不知道您想如何命名列,所以我没有做:))

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

您应该使用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')

如果在浮点数上操作,则不需要dtypefmt参数

暂无
暂无

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

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