【问题标题】:Python: How can I perform addition operator for two different text files?Python:如何为两个不同的文本文件执行加法运算符?
【发布时间】:2016-01-08 09:25:29
【问题描述】:

我想对文件A的两个文件执行加法操作,以逐行读取值,以便从文件B中添加值。如何为文件A启用逐行读取文件?给定文件A和B如下:

A.txt

2.0 1.0 0.5
1.5 0.5 1.0

B.txt

1.0 1.0 2.0

新文件中的预期输出

3.0 2.0 2.5
2.5 1.5 3.0

示例代码

import numpy as np

with open("a.txt")as g:
    p=g.read().splitlines()
    p=np.array([map(float, line.split()) for line in p])

with open("b.txt")as f:
    x=f.read().splitlines()
    for line in f:
        x=np.array([map(float, line.split()) for line in x])

XP=x+p       
print XP

我仍在改进代码。是否有其他替代方法可以这样做?

【问题讨论】:

  • 文件B.txt总是只有一行吗?
  • 对于这个例子,是的。
  • 你的问题是什么?你的代码不工作吗?你想让它更有效率吗?
  • 你为什么使用numpy
  • 更好的方法:1. 将b.txt 读入列表。迭代a.txt 并在迭代期间打印/存储添加的数据。不用把全部数据存起来再找numpy添加。

标签: python arrays list numpy addition


【解决方案1】:
from operator import add

b = []

with open("B.txt") as b_file:
    aux = b_file.readline()
    b   = [float(i) for i in aux.split()]

with open("A.txt") as a_file:
    output = open("output.txt", "a")
    for line in a_file:
        aux = [float(i) for i in line.split()]
        res = map(add, aux, b)
        output.write(str(res) + "\n")

【讨论】:

    【解决方案2】:

    也可以使用np.loadtxt,例如:

    In [11]: import numpy as np
    In [12]: A = np.loadtxt('path/to/A.txt')
    In [13]: B = np.loadtxt('path/to/B.txt')
    In [14]: A + B
    Out[14]: array([[ 3. ,  2. ,  2.5], [ 2.5,  1.5,  3. ]])
    

    将结果保存到 txt 文件同样简单:

    In [15]: np.savetxt('path/to/C.txt', A+B)
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      相关资源
      最近更新 更多