【问题标题】:How to sum and multiply the columns from two files?如何对两个文件中的列进行求和和相乘?
【发布时间】:2020-07-26 16:22:12
【问题描述】:

我有两个输入文件(input1.txtinput2.txt)。我会将第一个输入文件的第一列 (input1.txt) 乘以第二个输入文件的第三列 (input2.txt),然后将两个输入文件的第二列相加,然后将结果写入输出文件。

我尝试了下面的代码,但它给出了错误。如何修复我的代码?

错误:

SyntaxError: unexpected EOF while parsing

input1.txt:

2.5 1.2
5.5 6.5
3.2 6.3

input2.txt:

10.5 12.5 20.2
13.1 14.5 30.1
15.9 16.7 40.2

所需的输出.txt:

#first data second data
50.20   13.7
165.55  21.0
128.64  23.0

代码:

#!/usr/bin/env python3

with open('output.txt', mode='w') as f:
    with open("1.txt") as f1:
        data1 = f1.readlines()
        for line1 in data1:
            lines1 = line1.strip('')
            with open("2.txt") as f2:
                data2 = f2.readlines()
                for line2 in data2:
                    lines2 = line2.strip('')
                    f.write ("%.3f %.3f\n" % (float(lines1[0]*float(lines2[2]),
                                              float(lines1[1]+float(line1[1])))

【问题讨论】:

标签: python python-3.x


【解决方案1】:

将您的代码粘贴到编辑器后,我可以看到您在f.write() 调用末尾缺少一些右括号,这导致了SyntaxError: unexpected EOF while parsing 错误。添加那些缺少的),错误应该会消失。您还忘记了将行拆分为单独的元素。这将在进行float 转换时导致ValueError

您的代码没有错误:

with open('output.txt', mode='w') as f:
    with open("1.txt") as f1:
        data1 = f1.readlines()
        for line1 in data1:
            lines1 = line1.strip('').split()
            with open("2.txt") as f2:
                data2 = f2.readlines()
                for line2 in data2:
                    lines2 = line2.strip('').split()
                    f.write ("%.3f %.3f\n" % (float(lines1[0])*float(lines2[2]),
                                              float(lines1[1])+float(lines1[1])))

但是,逻辑需要调整。上面的代码从第一个输入文件迭代每一行,然后在里面你从第二个文件迭代每一行。这会给你一个笛卡尔积线,我不相信这是你想要的。

我们可以从它创建的错误输出中看到这一点:

50.500 2.400
75.250 2.400
100.500 2.400
111.100 13.000
165.550 13.000
221.100 13.000
64.640 12.600
96.320 12.600
128.640 12.600

相反,您可以并行迭代这两个文件。您可以使用zip 将两个输入文件聚合在一起,以在它们各自的列之间进行计算:

# Open both input files and output file
with open("input1.txt") as input1, open("input2.txt") as input2, open("output.txt", mode="w") as out:

    # Zip both inputs so we can do column matching
    for line1, line2 in zip(input1, input2):

        # Split lines into lists representing columns
        col1, col2 = line1.split(), line2.split()

        # Do both calculations
        # Round the first one to 2 decimal places and second one to 1 decimal place
        first_calc = round(float(col1[0]) * float(col2[2]), 2)
        second_calc = round(float(col1[1]) + float(col2[1]), 1)

        # Write to file
        out.write(f"{first_calc} {second_calc}\n")

这给出了以下output.txt

50.5 13.7
165.55 21.0
128.64 23.0

我会把最终的格式留给你做:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多