我有一个文件,其中包含以下格式的行:
CALSPHERE 1
1 00900U 64063C 20161.15561498 .00000210 00000-0 21550-3 0 9996
2 00900 90.1544 28.2623 0029666 80.8701 43.4270 13.73380512769319
CALSPHERE 2
1 00902U 64063E 20161.16836122 .00000025 00000-0 23933-4 0 9990
2 00902 90.1649 30.9038 0019837 126.9344 3.6737 13.52683749559421
……等等
我想将其解析为以下格式的词典:
{CALSPHERE 1:(1 00900U 64063C 20161.15561498 .00000210 00000-0 21550-3 0 9996, 2 00900 90.1544 28.2623 0029666 80.8701 43.4270 13.73380512769319),
CALSPHERE 2:(1 00902U 64063E 20161.16836122 .00000025 00000-0 23933-4 0 9990, 2 00902 90.1649 30.9038 0019837 126.9344 3.6737 13.52683749559421),...}
我不知道如何解析它,所以每三行就是关键,下面两行构成了值的元组。在python中实现这一点的最佳方法是什么
我试图为“每三行”添加一些逻辑,尽管它看起来有点复杂;差不多
with open(r"file") as f:
i = 3
for line in f:
if i%3=0:
key = line
else:
#not sure what to do with the next lines here
如果您的文件始终具有相同的分布(即“CALSPHERE”单词-或您希望它作为字典键的任何其他单词-后跟两行),您可以通过执行以下操作来实现所需的功能:
输出:
假设您的内容在file.txt中,您可以使用以下内容。 它应适用于任意数量的CALSPHERE关键字出现,以及不同数量的条目
相关问题 更多 >
编程相关推荐