0

示例 CSV 文件如下所示:

aa  danny  james    
1   3      6    

aa  bla h  mno  
1   3      6    

aa  danny  james    
1   10     15   

我想阅读这个 CSV 文件并以下列形式打印输出:

line number  james  danny
2            6      3
7            15     10

我尝试使用 re.search 开始查找具有值“Danny”的元素,但结果为错误。

import csv, re

file_location=r'D:\\'

spamReader = csv.reader(open(file_location))
for row in spamReader:
    if re.search('Danny', row):
        print(row)

我不确定是否必须使用字典或其他东西来获得所需的输出。

4

1 回答 1

0

这不是一个特别优雅的解决方案,但却是我能想到的最简单的方法。

>>> with open('test.test') as f:
...     num_to_scores = {}
...     for linenum, line in enumerate(f):
...         splitline = line.split()
...         if 'danny' in line and 'james' in line:
...             store_next_vals = True
...             dannyloc, jamesloc = splitline.index('danny'), splitline.index('james')
...         else:
...             if store_next_vals:
...                 num_to_scores[linenum] = {"james":splitline[jamesloc], "danny":splitline[dannyloc]}
...                 store_next_vals = False
>>> with open('out.test', 'w') as f:
...     f.write('line number,james,danny\n')
...     for linenum in num_to_scores:
...         f.write('%d,%s,%s\n' % (linenum, num_to_scores[linenum]['james'], num_to_scores[linenum]['danny']))
>>> print open('out.test').read()
line number,james,danny
1,6,3
7,15,10
于 2012-04-16T20:47:04.520 回答