简体   繁体   English

如何读取文本文件,以便在Python中生成浮点数组

[英]how to read a text file so that is produces an array of floats in Python

How to read a text file where each line has three floating point numbers, each with three digits after the decimal point. 如何读取文本文件,其中每行具有三个浮点数,每个浮点数在小数点后三位。 The numbers are separated by commas followed by one or more white spaces. 数字以逗号分隔,后跟一个或多个空格。 The text file (first four observations) looks like this: 文本文件(前四个观察结果)如下所示:

-0.340, 1.572, 0.616
-0.948, 1.701, 0.377
 0.105, 2.426, 1.265
-0.509, 2.668, 1.079

Desired output: 所需的输出:

array = [[-0.340 1.572 0.616],
[-0.948 1.701 0.377],
[0.105 2.426 1.265],
[-0.509 2.668 1.079]]
fh = open("YourFileName")
raw = fh.read()
fh.close()
data = [[float(i) for i in k.split(",")] for k in raw.split("\n")]

Use the csv module & convert to float, it's simple: 使用csv模块并转换为float,很简单:

import csv

with open("test.csv") as f:
    array = [[float(x) for x in row] for row in csv.reader(f)]

on this simple case you can get the same result without csv: 在这种简单的情况下,如果没有csv,则可以获得相同的结果:

    array = [[float(x) for x in row.split(",")] for row in f]

in both cases result is: 在这两种情况下,结果都是:

[[-0.34, 1.572, 0.616], [-0.948, 1.701, 0.377], [0.105, 2.426, 1.265], [-0.509, 2.668, 1.079]]

Use numpy load text as: 使用numpy加载文本为:

import numpy as np
x= np.loadtxt('YOUR_TXT_FILE.txt',comments='#',usecols=(0),unpack=True)

You should read the whole file, split into lines, and then split each line into values separated by comma. 您应该阅读整个文件,将其拆分为几行,然后将每一行拆分为以逗号分隔的值。 Last thing - use numpy.array to turn it into an array: 最后一件事-使用numpy.array将其转换为数组:

import numpy as np

filename = r'****.txt'

with open(filename) as f:
    txt = f.read()
    ls = []
    for line in txt.split('\n'):
        sub_ls = line.split(',')
        ls.append(sub_ls)

    print np.array(ls, dtype=np.float)
    # omitting the ", dtype=np.float" would result in a list-of-strings array

OUTPUT:

[[-0.34   1.572  0.616]
 [-0.948  1.701  0.377]
 [ 0.105  2.426  1.265]
 [-0.509  2.668  1.079]]

Just use numpy. 只需使用numpy。

import numpy as np

arr= np.loadtxt('data.txt',delimiter=',')
print("arr = {}".format(arr))

'''
arr = [[-0.34   1.572  0.616]
 [-0.948  1.701  0.377]
 [ 0.105  2.426  1.265]
 [-0.509  2.668  1.079]]
'''

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

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