繁体   English   中英

我如何读取以下类型的文本文件到数组/元组

[英]How do I read text file of following type in to array/tuple

这是文本文件的外观:

1.0778 0.86111
1.6173 0.94568
3.3376 1.565
1.1927 -0.90241
-1.0183 2.3423 
1.0599 1.3005
-2.9829 -1.1132
-0.01103 0.69469
2.9999 1.1401
-0.12478 -0.35958

我想读入10 * 2矩阵(在此示例中)

(实际上我的文本文件更长)

在一行中用numpy尝试一下:

import numpy as np

print(np.loadtxt('filex_txt',dtype=np.float32))

输出:

[[ 1.0778   0.86111]
 [ 1.6173   0.94568]
 [ 3.3376   1.565  ]
 [ 1.1927  -0.90241]
 [-1.0183   2.3423 ]
 [ 1.0599   1.3005 ]
 [-2.9829  -1.1132 ]
 [-0.01103  0.69469]
 [ 2.9999   1.1401 ]
 [-0.12478 -0.35958]]

您可以尝试以下方法:

data = [map(float, i.strip('\n').split()) for i in open('filename.txt')]

输出:

[[1.0778, 0.86111], [1.6173, 0.94568], [3.3376, 1.565], [1.1927, -0.90241], [-1.0183, 2.3423], [1.0599, 1.3005], [-2.9829, -1.1132], [-0.01103, 0.69469], [2.9999, 1.1401], [-0.12478, -0.35958]]
jmcmurray@host ~ $ printf "1.0778 0.86111 \n 1.6173 0.94568 \n 3.3376 1.565 \n 1.1927 -0.90241 \n -1.0183 2.3423 \n 1.0599 1.3005 \n -2.9829 -1.1132 \n -0.01103 0.69469 \n 2.9999 1.1401 \n -0.12478 -0.35958 \n" > test.txt
jmcmurray@host ~ $ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [x.split() for x in open("test.txt").readlines()]
[['1.0778', '0.86111'], ['1.6173', '0.94568'], ['3.3376', '1.565'], ['1.1927', '-0.90241'], ['-1.0183', '2.3423'], ['1.0599', '1.3005'], ['-2.9829', '-1.1132'], ['-0.01103', '0.69469'], ['2.9999', '1.1401'], ['-0.12478', '-0.35958']]

暂无
暂无

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

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