首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python -将2列文件转换为10列

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

Stack Overflow用户
提问于 2015-10-08 12:55:48
回答 2查看 55关注 0票数 1

亲爱的所有)我有一个问题,这对我来说是相当困难的,因为我刚刚开始做Python。因此,让我们想象一下,我们有一个2列文件,如:

代码语言:javascript
运行
复制
col_1 col_2
1     6 
2     7
3     8
4     9
5     10

我需要执行几个转换(使用不同的方程),这将创建额外的列(基本上,大约15列)。但我不知道如何将其包装为可读的和逻辑的代码。

让我向你展示我的想法(我确信它们是非常错误的,但我真的希望你的眼睛不会流血:)。首先,在这个问题上使用类是一个合适的想法吗?还是只做些功能?

代码语言:javascript
运行
复制
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方法。
  • 我要上课吗?还是只做些功能?应该是什么样子?

对我来说还有很多困难,但我应该从最一般的开始。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-08 13:09:45

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

代码语言:javascript
运行
复制
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):

代码语言:javascript
运行
复制
1 1
2 2
3 3

输出文件(titi.txt):

代码语言:javascript
运行
复制
1   1   2   -1
2   2   4   -2
3   3   6   -3
票数 2
EN

Stack Overflow用户

发布于 2015-10-08 14:18:55

你应该用numpy

代码语言:javascript
运行
复制
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参数

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33016495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档