2017-04-12 55 views
0

我想读的是有格式的输入文件:拆分逗号,换行,回车

[ '1,2,3 \ r \ n', '4,5,6' ]

我希望他们被分离,以便它看起来像

[ '1', '2', '3', '4', '5', '6']

我的代码看起来像

def importFile(file): 
with open(file) as f: 
    content = f.readlines() 
    print content 
    for line in content: 
     tempList = line.split(',') 
    print tempList 

不幸的是,我得到现在的问题是

[ '4', '5', '6']

哪儿了我做错了?谁能帮我?

+1

您正在覆盖'for'循环内'tempList'的内容,因此您只有最后一次迭代的内容。 – mrogers

+0

@ mrogers我做了一些小改动,但是现在我得到了'[['1,2,3 \ r \ n'],['4,5,6']]'。接下来我应该做什么? – ThomasWest

回答

1

重申我的意见:问题是您在for循环(文件的每一行)的每次迭代中覆盖tempList。以下是您可以解决问题的一种方法。我借用正则表达式将数字从行中取出,以从Python: Extract numbers from a string中除去\r\n。 该解决方案的核心是第二个for循环,遍历每行的内容。

import re 

def importFile(file): 
    with open(file) as f: 
     content = f.readlines() 
     print content 
     result = [] 
     for line in content: 
      tempList = line.split(',') 
      for x in tempList: 
       result.append(re.findall(r'\d+', x)[0]) 
     print result 
+0

我明白了,所以事实证明我只需要一个地方直接存储分割结果。谢谢。 – ThomasWest

+0

我相信您可以通过其他解决方案获得更多创意。这只是第一个想到的问题。 – mrogers