简体   繁体   English

Python:读入文件,其中数字为分数或浮动以视为浮点数

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

Python question: Python问题:

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. 我有一个.txt文件,由数字组成,可以是分数或浮点数。 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. 例如,我在我的文件中添加了1/4作为数字,我得到以下内容。

     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)]

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

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