我有一个文本文件:
S1645BS5010 11 2558180123.98N0185135.88W 91175.71997031.83098.5346232936
R0001 91823.71996951.410.80002 91824.81996938.811.00003 91825.91996926.311.01
R0004 91827.01996913.811.10005 91828.11996901.311.10006 91829.21996888.711.11
R0007 91830.31996876.211.20008 91831.41996863.711.20009 91832.51996851.211.31
S1645BS5010 13 2563180126.23N0185138.97W 91086.31997103.13098.5346233020
R0001 91822.91997032.810.90002 91824.01997020.311.10003 91825.21997007.711.21
R0004 91826.31996995.211.20005 91827.41996982.711.30006 91828.51996970.211.31
R0007 91829.51996957.611.40008 91830.61996945.111.40009 91831.71996932.611.51
我想从以“S”开头的行中提取[21:25]处的字符,然后从以“R”开头的每一行中用索引[23:26]、[49:54]和[75:80]处的字符创建一个键值对,直到遇到以“S”开头的下一行,然后重复该过程,因此,可以用这些键值对制作一个字典,以便于绘图。你知道吗
到目前为止,我已经开始在提取列表中的“S”值后制作一个列表:
file='Z:\Sei\text.pp'
shot_no=[]
with open(file , 'r') as f:
for line in f:
if len(line) > 0 and line.startswith('S'):
shot_no.append(line[21:25])
但在如何使用它来建立一个字典的困惑。你知道吗
有人能帮忙吗。你知道吗
一步一步地通过它。你在正确的轨道上。 如果您逐行读取文件,那么您有3个案例:
因此,请考虑:
使用collections.defaultdict
输出
我认为您需要修复索引,它们不是您显示为输出的内容。我也不知道你想转换成浮点还是十进制。你知道吗
如果要保留插入顺序-可能需要使用OrderedDict,然后调整添加值的部分。你知道吗
使用collections.OrderedDict
输出
编辑:在python3.7+中,常规dict也可以,因为根据文档“dict对象的插入顺序保存性质已经声明为Python语言规范的一个正式部分”。在3.6中,此功能被视为实现细节,不应依赖。因此,在3.7之前,必须使用OrderedDict。你知道吗
请注意,字典必须有唯一的键。
因此,您必须考虑作为键输入的内容。
如果您使用的是
line[:11]
,并且存在重复项,那么最后一个键将丢失一些数据,值对将覆盖字典中已有的键。你知道吗相关问题 更多 >
编程相关推荐