将文本文件转换为numpyarray

时间:2016-07-05 08:51:34

标签: python-2.7 numpy

我是python的新手。我有一个.txt文件

SET = 20,21,23,21,23 
      45,46,42,23,55

有很多行。如何将此txt文件转换为忽略空格和逗号的数组?任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:1)

l1=[]
file = open('list-num')
for l in file:
    l2 = map(int,l.split(','))
    l1 = l1 + l2 
print l1

答案 1 :(得分:1)

您的数据如下:

SET 1 = 13900100,13900141,13900306,13900442,13900453,13900461, 13900524,13900537,13900619,13900632,13900638,13900661, 13900665,13900758,13900766,13900825,13900964,13901123, 13901131,13901136,13901141,13901143,13901195,13901218,

您可以使用numpy命令:np.genfromtxt ()

import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt("text.txt", delimiter=",")

data = data[np.logical_not(np.isnan(data))] #Remove nan value

print data

我明白了:

[ 13900141.  13900306.  13900442.  13900453.  13900461.  13900524.
  13900537.  13900619.  13900632.  13900638.  13900661.  13900665.
  13900758.  13900766.  13900825.  13900964.  13901123.  13901131.
  13901136.  13901141.  13901143.  13901195.  13901218.]

它应该工作;)

------------------------------------

其他方式:

import numpy as np

f = open("text.txt", "r") #Open data file
data = f.read() #Read data file

cut = data.split() #Split data file

value = cut[2] #Pick the value part

array = np.array(value) #Value becomes an array

print array

我明白了:

13900100,13900141,13900306,13900442,13900453,13900461,13900524,13900537,13900619,13900632,13900638,13900661,13900665,13900758,13900766,13900825,13900964,13901123,13901131,13901136,13901141,13901143,13901195,13901218