简体   繁体   中英

Python: Read in file with numbers that are fractions or floating to treat as floating numbers

Python question:

with open(input, "rt") as f:
X = [map(float, line.split()) for line in f.readlines()[1:R]]  <<problem here
X = asarray(X, dtype=float) 

I have a .txt file consisting of numbers that could either be fractions or floating point numbers. I read them into my code as an array of floating point numbers here. However, this only works for floating numbers. When you add a fraction as one of the numbers in my input files, an error occurs. For example, I added 1/4 as a number in my file, and I get the following.

     with open(input, "rt") as f:
--->     X = [map(float, line.split()) for line in f.readlines()[1:R]] 
         X = asarray(X, dtype=float)


ValueError: invalid literal for float(): 1/4. 

How do I fix this? (so that it can read fractions and floating numbers and also convert these fractions into floating when reading them)

>>> from fractions import Fraction
>>> [float(Fraction(x)) for x in '0.25 1/4'.split()]
[0.25, 0.25]

so you need

X = [[float(Fraction(x)) for x in line.split()] for line in f.readlines()[1:R]]

note: to avoid making a temporary list of the whole file it may be preferable to use

from itertools import islice
with open(input, "rt") as f:
    X = [[float(Fraction(x)) for x in line.split()] for line in islice(f, 1, R)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM