计算两个文件之间的商并将其写入另一个文件

编程入门 行业动态 更新时间:2024-10-28 21:23:16
本文介绍了计算两个文件之间的商并将其写入另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用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.

更多推荐

计算两个文件之间的商并将其写入另一个文件

本文发布于:2023-10-26 07:34:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   两个   并将其

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!