我的CSV看起来像这样:
Point ID,Northing,Easting,Elevation,Attributes,Feature Code,Combined Scale Factor
1000,5000000,400000,100,Pipe_ln:pipeline_ln:DEPTH:2.5|Pipe_ln:pipeline_ln:COVER_TYPE:DIRT/GRASS|Pipe_ln:pipeline_ln:COMPANY:ABC|Pipe_ln:pipeline_ln:SIZE:10|Pipe_ln:pipeline_ln, pipe_ln,0.999665
如您所见,Attributes
列包含
Pipe_ln:pipeline_ln:DEPTH:2.5|Pipe_ln:pipeline_ln:COVER_TYPE:DIRT/GRASS|Pipe_ln:pipeline_ln:COMPANY:ABC|Pipe_ln:pipeline_ln:SIZE:10|Pipe_ln:pipeline_ln
我想从中提取DEPTH:2.5
。 (有大约50行,深度因行而异)
到目前为止,我的代码如下:
field_list = []
with open(infile, 'rb') as raw_csv:
reader = DictReader(raw_csv, delimiter=',')
fieldnames = reader.fieldnames + ['DEPTH']
with open(outfile, 'wb') as out_csv:
writer = DictWriter(out_csv, delimiter=',', fieldnames=fieldnames)
headers = {}
for header in writer.fieldnames:
headers[header] = header
writer.writerow(headers)
for row in reader:
if 'Pipe_ln' in row['Feature Code']:
field_list.append(row['Attributes'].replace("|", ":").split(":"))
writer.writerow(row)
DEPT_vals = header_tuple(field_list)
在DictReader下,我手动添加DEPTH
字段然后在我的代码的最后一行,header_tuple
是我写的一个函数,它导致形式的元组列表[(&#39 ; DEPTH',2.5),(' DEPTH',2.1)等...]
我无法以正确的方式或以任何方式绕过我的头来获取要在DEPTH
标题下写入的元组深度值。有什么建议?我采取了不必要的步骤吗? (有人建议我将我想要的信息从ATTRIBUTES
提取到元组中,这就是为什么我这样做的原因。)