简体   繁体   English

从文本文件读取时如何将字符串转换为浮点数

[英]How to convert a string into a float when reading from a text file

Hey guys so I have a text file that I am trying to read from and receive every number string and convert it into a float. 大家好,我有一个试图读取和接收每个数字字符串并将其转换为浮点型的文本文件。 But every time I try it, it says "cannont convert string to float". 但是每次我尝试它时,都会显示“无法将字符串转换为浮点数”。 Why is this happening? 为什么会这样呢? Thanks! 谢谢!

try:
    input_file = open("Dic9812.TFITF.encoded.txt","r")
    output_fileDec = open("Dic9812.TFITF.decoded.txt","w")
    output_fileLog = open("Dic9812.TFITF.log.txt","w")
except IOError:
    print("File not found!")

coefficientInt = input("Enter a coefficient: ")
coefficientFl = float(coefficientInt)
constInt = input("Enter a constant: ")
constFl = float(constInt)

try:
    for line in input_file:
        for numstr in line.split(","):
            numFl = float(numstr)
            print(numFl)
except Exception as e:
    print(e)

The file looks like this: 该文件如下所示:

135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0

It ends up printing the numbers but at the end it says: cannot convert string to float: 最终打印出数字,但最后说:无法将字符串转换为浮点数:

At the end of the second line, you have a comma, so you have an empty string in the list. 在第二行的末尾,您有一个逗号,因此列表中有一个空字符串。 float('') raise an exception, hence your error: float('')引发异常,因此出现错误:

for line in input_file:
    for numstr in line.split(","):
        if numstr:
            try:
                numFl = float(numstr)
                print(numFl)
            except ValueError as e:
                print(e)

As said in comments, avoid to catch Exception and try to have the minimum lines of code in a try/except to avoid silent errors. 如评论中所述,避免捕获Exception并尝试在try/except中使用最少的代码行,以避免产生无提示错误。

Input f 输入f

135.0,201.0,301.0
152.0,253.0,36.0,52.0
53.0,25.0,369.0,25.0

Python f.py python f.py

import sys

for line in sys.stdin.readlines():
    fs = [float(f) for f in line.split(",")]
    print fs

Usage 用法

$ python f.py < f

Output 产量

[135.0, 201.0, 301.0]
[152.0, 253.0, 36.0, 52.0]
[53.0, 25.0, 369.0, 25.0]

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

相关问题 从SQL数据库读取时,熊猫无法将字符串转换为浮点数 - Pandas could not convert string to float when reading from SQL database 无法将字符串转换为浮点型-从fil中读取 - Could not convert string to float - Reading from the fil 读取文本文件并将字符串转换为浮点数 - Reading a text file and converting string to float Python:ValueError:无法将字符串转换为浮点数:读取输入文件以应用随机森林时“隔离” - Python: ValueError: could not convert string to float: 'Isolated' when reading input file for applying random forest 从Excel提取数据时如何从字符串转换为浮点数 - How to convert from a string to a float when taking the data from excel 将csv文件读取到python ValueError:无法将字符串转换为float - Reading csv file to python ValueError: could not convert string to float 从字符串读取浮点数 - Reading a float from string 读取二进制文件但想转换为文本/字符串 - Reading binary file but want to convert to text/string ValueError:无法将字符串转换为浮点型:从DictReader读取 - ValueError: Could not convert string to float: Reading from DictReader 读取文件内容时,无法将str转换为float(Python) - Unable to convert str to float when reading contents of a file (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM