首页 > 解决方案 > 如何阅读 csv 文件中的注释并使用它们?

问题描述

#StationCode:4845    
#InstrumentKind: CSV  (20191216114518_4845)    
#StartTime:2019/12/16 11:45:28.010    
#RecordLength(sec):103.00    
#SampleRate(Hz): 100    
#AmplitudeUnit:  gal. DCoffset(corr)    
#AmplitudeMAX. a:   15.133 ~   -22.371    
#AmplitudeMAX. b:   70.222 ~   -37.683    
#AmplitudeMAX. c:   13.398 ~   -11.425    
#Intensity:5.0 touC:0.059 PGA:74.4gal PGV:27.7mm/s    
#Time sync.:NTP    
#DataSequence: Time; a; b; c; Pd; Displacement    
#Data: 4F10.3   

所以这就是我拥有 csv 文件的方式,这些注释位于文件的开头。现在我怎么可能一一解析这些评论并使用它们?在阅读 csv 文件时,我遇到了仅帮助我删除或忽略这些评论的文章。如果我在任何地方弄错了,请纠正我。

标签: pythoncsv

解决方案


一个一个地使用它们并不清楚你的意思。但是要将这些值放入列表中。你可以使用正则表达式。

根据您的需要,您可以进一步处理评论以清理它们。

添加了一个简单的理解来清理空格并添加到字典中。


s = '''#StationCode:4845    
#InstrumentKind: CSV  (20191216114518_4845)    
#StartTime:2019/12/16 11:45:28.010    
#RecordLength(sec):103.00    
#SampleRate(Hz): 100    
#AmplitudeUnit:  gal. DCoffset(corr)    
#AmplitudeMAX. a:   15.133 ~   -22.371    
#AmplitudeMAX. b:   70.222 ~   -37.683    
#AmplitudeMAX. c:   13.398 ~   -11.425    
#Intensity:5.0 touC:0.059 PGA:74.4gal PGV:27.7mm/s    
#Time sync.:NTP    
#DataSequence: Time; a; b; c; Pd; Displacement    
#Data: 4F10.3 '''

import re

comments = re.findall(r'#(.*)', s)

keys = [x.split(':')[0].strip() for x in comments]
values = [x.split(':')[1].strip() for x in comments]

comments = dict(zip(keys,values))

for k,v in comments.items():
    print(f"key: {k} ---- value: {v}")


# Output: 
#key: StationCode ---- value: 4845
#key: InstrumentKind ---- value: CSV  (20191216114518_4845)
#key: StartTime ---- value: 2019/12/16 11
#key: RecordLength(sec) ---- value: 103.00
#key: SampleRate(Hz) ---- value: 100
#key: AmplitudeUnit ---- value: gal. DCoffset(corr)
#key: AmplitudeMAX. a ---- value: 15.133 ~   -22.371
#key: AmplitudeMAX. b ---- value: 70.222 ~   -37.683
#key: AmplitudeMAX. c ---- value: 13.398 ~   -11.425
#key: Intensity ---- value: 5.0 touC
#key: Time sync. ---- value: NTP
#key: DataSequence ---- value: Time; a; b; c; Pd; Displacement
#key: Data ---- value: 4F10.3



推荐阅读