2017-12-27 493 views
0

我从txt文件中读取元素,并且想要将元素写入数组,我知道我必须使用substring方法,但我不知道如何生成数组使用子串方法。如何在Python中将元素写入数组

example.txt的文件包括

001, A, 50, 70, 65 
002, B, 25, 55, 80 
003, C, 60, 40, 85 
004, D, 75, 55, 70 
005, E, 40, 40, 45 
006, F, 35, 25, 85 

我的Python代码:

file = open("example.txt", "r") 
a = file.read() 
print(a) 

我需要生成30种元素的多维(5×6)阵列,可以阅读使用此代码此文件的元素但我不知道如何将它们写入数组。

+1

看'](https://docs.python.org/2/library/string.html#string.split)和['str.strip'](https://docs.python.org/2/library/string。 html#string.strip) – schwobaseggl

回答

2

为了得到多维数组,你需要逐行读取文件中的行,并用逗号在我previous answer

# Prepare result array: 
array = [] 
# Open file 
with open("example.txt", "r") as f: 
    # read the contents of file line by line: 
    for line in f: 
     # split current line by comma to get array of items from it 
     array_parts = line.split(",") 
     # filter elements, removing empty, and stripping spaces: 
     array_parts = [item.strip() for item in array_parts if item.strip() != ""] 
     # add line's items into result array: 
     array.append(array_parts)   
# Printing result: 
print(array) 
+0

我收到一个错误 – hbakan

+0

修正了它。据说,解决这个错误将是你的功课:) – MihanEntalpo

+0

非常感谢,我了解到我应该做的。 – hbakan

1

您需要作为字符串来读取数据,并在由逗号和换行符把它分解:

# Open file 
with open("example.txt", "r") as f: 
    # read the contents and replace "\n" characters by commas 
    thedata = f.read().replace("\n", ",") 
    # split it by "," creating an array 
    array = thedata.split(",") 
    # if it's needed, remove empty elements and trim spaces: 
    array = [item.strip() for item in array if item.strip() != ""] 
# Printing result: 
print(array) 
+0

你也应该考虑这些行。 – schwobaseggl

+0

看起来像这样,但问题的作者说:“我需要生成30个元素数组”,我已经回答了这个需求:) – MihanEntalpo

+0

如果你只用逗号分割,我认为你不会得到满30 ;) – schwobaseggl

2

所有你需要的是沿str.split()str.strip()为:

with open("example.txt") as f: 
    my_list = [w.strip() for l in f for w in l.split(',')] 
#    ^to remove extra white-spaces 

这将返回my_list列表为:

>>> my_list 
['001', 'A', '50', '70', '65', '002', 'B', '25', '55', '80', '003', 'C', '60', '40', '85', '004', 'D', '75', '55', '70', '005', 'E', '40', '40', '45', '006', 'F', '35', '25', '85'] 
+3

这是最干净和最Pythonic的方法! – schwobaseggl

3

你可以这样做,使用split

In [14]: print map(str.strip,sum([i.split(',') for i in open("example.txt").split('\n')],[])) 
['001', 'A', '50', '70', '65', '002', 'B', '25', '55', '80', '003', 'C', '60', '40', '85', '004', 'D', '75', '55', '70', '005', 'E', '40', '40', '45', '006', 'F', '35', '25', '85'] 

不同的方法压扁名单,

result = map(str.strip,[item for sublist in [i.split(',') for i in txt.split('\n')] for item in sublist]) 
+2

男孩,我爱那些Python单行:) – noamgot

+0

但是请注意,列出展平的总和方法具有二次时间复杂性。你也不会剥夺空间。 – schwobaseggl

+0

@schwobaseggl感谢您的意见, –

2

很多体面的理解基于解决方案的周围。下面是一个使用mapitertools.chain

from itertools import chain 
with open("example.txt", "r") as f: 
    array = list(chain(*(map(str.strip, line.split()) for line in f))) 
0

分割每行,就像如果你想为了保持CSV文件的格式,并有一个二维数组,然后可能先设置二维数组,然后遍历文件并添加值可能是要走的路。

array = [] 

for row in range(0,6): 
    array.append([]) 
    for col in range(0,5): 
     array[row].append(" ") 

print(array) 

然后添加你瓦莱斯而不是用空间,导入的文件,通过各行进行迭代,并为每个值在它[`str.split添加到相应的空间,在你的二维数组