python - 如何阅读 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 文件时,我遇到了仅帮助我删除或忽略这些评论的文章。如果我在任何地方弄错了,请纠正我。
解决方案
一个一个地使用它们并不清楚你的意思。但是要将这些值放入列表中。你可以使用正则表达式。
根据您的需要,您可以进一步处理评论以清理它们。
添加了一个简单的理解来清理空格并添加到字典中。
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
推荐阅读
- python - models.ForeignKey 是否接受自身的实例作为默认值?
- python - 如何使用 tkinter 将用户选择的颜色分配给 Python 列表中的每个元素
- python-3.x - 在熊猫中处理工作表后保存工作簿
- r - 时间序列的滞后回归
- azure - 无法使用 Azure SignalR 服务连接到集线器
- javascript - 滚动到视图中时启动动画
- json - 如何将 bash 命令输出添加到漂亮格式的 json git log
- go - ROT13 使用字节而不是字符串
- python - 如何从“ir.property”模型中获取价值。奥多 14
- r - 显示警告:Shiny 中 :: NA/NaN 参数中的错误