简体   繁体   English

如何将科学记数法值转换为浮点数

[英]How to convert scientific notation value to float

I have txt files in the format:我有以下格式的txt文件:

 6.3894e+02 1.7316e+02 6.6733e+02 1.9942e+02 9.8697e-01
 6.4355e+02 1.7514e+02 6.8835e+02 2.0528e+02 9.7908e-01

I want to convert all these values into float as in:我想将所有这些值转换为浮点数,如下所示:

 638.94 173.16 667.33 199.42 98.697
 643.55 175.14 688.35 205.28 97.908

My code is:我的代码是:

   import os
   for i in os.listdir():
       if i.endswith(".txt"):
          with open(i, "r+") as f:
               content = f.readlines()
               for line in content:
                   f.write(float(line))

You can't update a file in place like that.你不能像这样就地更新文件。 You can use the fileinput module for that.您可以fileinput使用fileinput模块。

You need to split the line at whitespace, parse each of the numbers as floats, then write them the way you want.您需要在空格处拆分行,将每个数字解析为浮点数,然后按照您想要的方式编写它们。

You can also use glob() to match all the .txt files instead of using os.listdir() and .endswith() .您还可以使用glob()来匹配所有.txt文件,而不是使用os.listdir().endswith()

import fileinput
from glob import glob

for i in glob("*.txt"):
    with fileinput.input(files=i, inplace=True) as f:
        for line in f:
            nums = map(float, line.split())
            print(*nums)

Try something like this for all the rows:对所有行尝试这样的操作:

   text = "6.3894e+02 1.7316e+02 6.6733e+02 1.9942e+02 9.8697e-01"
    numbers = text.split()
    numbers_float = [float(x) for x in numbers]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将科学记数法转换为浮点数 - Convert Scientific Notation to Float 如何在Python中将浮点表示法转换为10种科学表示法的功效? - How to convert float notation to power of 10 scientific notation in Python? 将字符串(科学计数法)转换为浮点数 - Convert string (in scientific notation) to float Pandas / 如何将存储为字符串的科学记数法转换为浮点数? - Pandas / How to convert scientific notation stored as strings into float? Pandas将科学记数法中的浮点数转换为字符串 - Pandas convert float in scientific notation to string Python 将字符串转换为无科学记数法的浮点数 - Python Convert String to Float without Scientific Notation 如何在matplotlib中将浮点值设置为科学计数法? - How to set float values as scientific notation in matplotlib? 是否有一个python模块将值和错误转换为科学记数法? - Is there a python module that convert a value and an error to a scientific notation? 如何将pandas DataFrame中的列从str(科学计数法)转换为numpy.float64? - How do I convert a column from a pandas DataFrame from str (scientific notation) to numpy.float64? 将float64 numpy数组转换为非科学记数法的浮点数 - Convert float64 numpy array to floats not in scientific notation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM