在过滤字符Python 2.7时将txt文件数据导入数组

时间:2014-12-11 16:16:19

标签: python python-2.7

您好我想从文本文件text.txt导入数据并将其导入数组中删除逗号和\ n。文件的数据类似于以下内容:

1,2,3,4,5,6,7,8,9,0
0,9,8,7,6,5,4,3,2,1
3,5,2,7,6,5,5,2,6,1
1,2,3,4,5,6,7,8,9,0
0,9,8,7,6,5,4,3,2,1
0,9,8,7,6,5,4,3,2,1
3,5,2,7,6,5,5,2,6,1

我到目前为止的代码如下:

def ReadFile():
  myFile = open('text.txt','r')
  lines = myFile.readlines()
  print lines #print raw data

  lines[:] = [line.rstrip('\n') for line in lines]
  print lines #print lines after removing \n

  lines = lines.replace(",", "")
  print lines #print after removing commas

  lines = map(int, lines)
  print lines #print lines after converting to int

我无法删除逗号,我无法转换为int。错误消息如下:

AttributeError: 'list' object has no attribute 'replace'
ValueError: invalid literal for int() with base 10: '1,2,3,4,5,6,7,8,9,0'

由于

4 个答案:

答案 0 :(得分:1)

试试这个:

def read_file(filename):
    with open(filename) as f:
        return [ [int(item) for item in line.split(',')]
                            for line in f ]

>>> print read_file('text.txt')
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
 [0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [3, 5, 2, 7, 6, 5, 5, 2, 6, 1],
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
 [0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [3, 5, 2, 7, 6, 5, 5, 2, 6, 1]]

答案 1 :(得分:1)

你正在努力做到这一点:

def ReadFile():
    array = []
    with open('textfiledata.txt', 'rt') as myFile:
        for line in myFile:
            array.append(map(int, line.split(',')))
    return array

print ReadFile()

输出:

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
 [0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [3, 5, 2, 7, 6, 5, 5, 2, 6, 1],
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
 [0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [0, 9, 8, 7, 6, 5, 4, 3, 2, 1],
 [3, 5, 2, 7, 6, 5, 5, 2, 6, 1]]

答案 2 :(得分:0)

使用generator即可:

# create a generator
def ReadFile():
   with open('text.txt','r') as myFile:
       for line in myFile:
           # send out the line just processed
           yield map(int, line.strip().split(','))

# cast the generator to a  list for printing
print list(ReadFile())

答案 3 :(得分:-1)

在使用逗号和int强制转换之前,您可以执行以下操作:

for i in lines:
     my_list.append(i)