计算两个文件之间的商并将其写入另一个文件 [英] Calculating the quotient between two files and writing it into another file
问题描述
使用Python,我有两个大文件(均长),其中数字用空格分开:
Using Python, I have two large (equally long) files in which the numbers are divided by spaces:
0.11158E-13 0.11195E-13 0.11233E-13 ...#file1
0.11158E-13 0.11195E-13 0.11233E-13 ... # file1
0.11010E-13 0.11070E-13 0.11117E-13 ...#file2
0.11010E-13 0.11070E-13 0.11117E-13 ... # file2
这些值存在差异,我想获得相对的差异并将它们以相同的格式写入第三个文件中. 我可以为第一个值做到这一点,但是在对流程进行迭代(以便计算所有值)时遇到问题.
There are differences in the values and I would like to get the relative differences and writing them in the same format into a third file. I can do it for the first value but have problem when it comes to ITERATING the process (so that all values are computed).
这是代码(我是python代码的新手):
This is the code (I am new to the python code):
with open('ex1.idl', 'r') as f1: #this opens the first file
with open('ex2.idl', 'r') as f2: #this opens the second file
f1 = f1.read(13) # reading the length of the value (ex1.idl)
f2 = f2.read(13) # reading the length of the value (ex2.idl)
f1 = float(f1) #assigning the numerical value for the string
f2 = float(f2) #assigning the numerical value for the string
c = f1/f2 #calculating relative values
with open('ex3.txt', 'w') as f3: #opening the new file and
f3.write(str(c)) #writing into the new file as a string
这是走的路还是应该以其他方式走?非常感谢您的回答.
Is this the way to go or should I go with a different approach? An answer is very much appreciated.
推荐答案
看起来您的文件各有一行.因此,获取每个文件中数字的最简单方法是只读取文件的全部内容,剥离所有不需要的字符,然后在空白处分开以分隔浮点值.在空格上分割将为您提供strings
列表,然后您可以将其强制为floats
.此时,您应该有两个浮点值列表,也就是说,当您使用zip
和map
函数的组合来执行除法运算时.以下是说明:
It looks like your files have one line each. So the easiest way to get the numbers in each file is to just read the entire content of the file, strip any unneeded characters and then split on the whitespace separating the floating point values. Splitting on the space will give you a list of strings
, which you can then coerce to floats
. At this point, you should have two lists of floating point values, and that is when you use the combination of the zip
and map
functions to carry out the division operation. The following is an illustration:
with open('ex1.idl') as f1, open('ex2.idl') as f2:
with open('ex3.txt', 'w') as f3:
f1 = map(float, f1.read().strip().split())
f2 = map(float, f2.read().strip().split())
for result in map(lambda v: v[0]/v[1], zip(f1, f2)):
# This writes the results all in one line
# If you wanted to write them in multiple lines,
# then you would need replace the space character
# with a newline character.
f3.write(str(result)+" ")
我希望这证明是有用的.
I hope this proves useful.
这篇关于计算两个文件之间的商并将其写入另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!