【问题标题】:Loop for Parsing complex tab delimited/csv files in Python用于在 Python 中解析复杂制表符分隔/csv 文件的循环
【发布时间】:2013-11-20 22:22:00
【问题描述】:

为了清楚起见,我对编程很陌生,而且我使用的是 Python 3.3!现在我在相同的基本布局中有很多文件。每个文件有 9 列,制表符分隔和可变数量的标题行 - 但大多数有 5 行。行或列没有标题!

看起来像这样:

#header1
#header2
#header3
#header4
#header5
ID1    asdf    asdk    asdfk    asdfkl    adsfkln    askdlfn   safsda    asdf    Notes1..
ID2    asdf    asdk    asdfk    asdfkl    adsfkln    askdlfn   safsda    asdf    Notes2..
ID3    asdf    asdk    asdfk    asdfkl    adsfkln    askdlfn   safsda    asdf    Notes3..
ID4    asdf    asdk    asdfk    asdfkl    adsfkln    askdlfn   safsda    asdf    Notes4..

我想要的唯一信息是第一列,其中包含 ID,最后一列包含有关每个 ID 的注释。我正在为类似这样的字典拍摄

{'ID1': [notes1...]
 'ID2': [notes2...]....
 'ID1234': [notes1234...]}

但我也会对字典列表或类似的东西感到满意。

所以我首先将文本转换为列表列表,以便我可以按索引查找条目:

import csv

list_all = list(csv.reader(open(r'complex_tabbed_file.gff', 'rb'), delimiter='\t'))

d = dict()
ID = data[5][0]     #starting at 5 to skip the header lines
notes = data[5][8]
d[ID]= notes

print (d)

这为我提供了我正在寻找的信息,但我一次只读取一个条目。我需要创建一个循环,该循环将读取包含数百个条目的整个文件......关于起点的建议?

我研究发现:Read specific columns from a csv file with csv module?

描述了类似的情况,但编码有点过头了。由于我是新手,我很难将这个示例应用到我的特定案例中 =(

这是我尝试过的迭代:

i=0

if i < 4:
    i= i+1

if i >= 5:
    ID = list_all[i][0]
    notes = list_all[i][8] 
    i= i+1

print (d)

这会返回一个空字典 ( d={ } ) 不好。

也试过了

d = dict()  
i=5
for line in list_all: 
    ID = list_all[i][0]
    notes = list_all[i][8] 
    i = i+1

print (d)

这给出了非常可爱的“列表索引超出范围”错误消​​息。非常感谢任何建议,谢谢!

【问题讨论】:

    标签: python parsing csv dictionary


    【解决方案1】:

    您可以解决它遍历每一行并丢弃那些只有一个字段(标题)的:

    import csv
    import sys
    
    d = dict()
    
    with open(sys.argv[1], newline='') as csvfile:
        csvreader = csv.reader(csvfile, delimiter='\t')
        for row in csvreader:
            if len(row) == 1: continue
            _d = {row[0]: [row[-1]]}
            d.update(_d)
    
    print(d)
    

    像这样运行它:

    python3 script.py infile
    

    产生:

    {
        'ID4': ['Notes4..'], 
        'ID1': ['Notes1..'], 
        'ID2': ['Notes2..'], 
        'ID3': ['Notes3..']
    }
    

    【讨论】:

      【解决方案2】:

      阅读您的代码确实让我想知道您是否阅读过文档?第一个小示例循环遍历所有条目/行...:http://docs.python.org/2/library/csv.html

      无论如何,csv 模块无法过滤掉 cmets,但你可以使用 python 自己的filter

      import csv
      d = dict()
      f = file('data.csv')
      data = csv.reader(filter(lambda row: row[0]!='#', f), delimiter='\t')
      for row in data:
        #print row
        d.update({row[0]: row[1:]})
      f.close()
      print(d)
      

      您也可以考虑使用DictReader 而不是reader...

      【讨论】:

        【解决方案3】:

        有时完全跳过csv 模块会更容易:

        from pprint import pprint
        d = dict()
        with open('complex_tabbed_file.gff') as input_file:
          for line in input_file:
            line = line.split('\t')
            if len(line) > 1:
              d[line[0]] = [line[-1].strip()]
        
        pprint(d)
        

        【讨论】:

          猜你喜欢
          • 2011-12-12
          • 2012-06-19
          • 1970-01-01
          • 1970-01-01
          • 2013-10-20
          • 2015-09-13
          • 2019-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多