简体   繁体   English

如何从python中的文本文件中获取浮点数?

[英]How to get floats from text file in python?

Hi I am new to python and I have a textfile .txt with the following structure: 嗨,我是python的新手,并且我有一个具有以下结构的文本文件.txt:

Text1     31332.22342
Text2     293023.32323
Text3     32332.32323

What is the easiest way to get those numbers into an array? 将这些数字放入数组的最简单方法是什么? Cheers! 干杯!

You can read the file and split it into aa list, then iterate through the list and try to convert to a float, if its successful then add it to the floats list. 您可以读取文件并将其拆分为一个列表,然后遍历该列表并尝试转换为浮点数,如果成功,则将其添加到浮点数列表中。 like the following: 如下所示:

    with open('file.txt', 'r') as f:
        data = f.read().split()
        floats = []
        for elem in data:
            try:
                floats.append(float(elem))
            except ValueError:
                pass
        print floats

output: 输出:

[31332.22342, 293023.32323, 32332.32323]

You also can use numpy genfromtxt function. 您还可以使用numpy genfromtxt函数。 something like this: 像这样的东西:

text_file.txt text_file.txt

Text1     31332.22342
Text2     293023.32323
Text3     32332.32323

python shell 蟒蛇壳

>>> import numpy as np
>>> numbers = np.genfromtxt('text_file.txt', usecols=1 )

output 输出

[  31332.22342  293023.32323   32332.32323]

To get propert validation of your data type try this: 要对您的数据类型进行属性验证,请尝试以下操作:

import numpy as np
data = np.genfromtxt("test.txt", usecols=1, dtype=float)

Output: 输出:

[  31332.22342  293023.32323   32332.32323]

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

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