【问题标题】:python split lines of file maybe every 2 lines and create dictionarypython拆分文件行可能每2行并创建字典
【发布时间】:2018-04-23 15:20:00
【问题描述】:

我有一个类似的文件:

AFA MT 0 0  1.22 259 169 FOD 0 50.01 1.3  1.370  0.00  -0.02  1.78 0  0.0
                        S 2 50.620 1.960 2.452 0.00 -0.49 0.31
MKE MS 0 0  4.22 256 149 MDO 1 30.00 1.4  2.370  3.00  -0.52  4.82 0 0.0
KTE KL 0 0  1.22 259 169 FID 0 10.01 2.0  2.470  1.00  -0.12  0.78 1  1.0
                        S 3 70.610 1.960 2.52 0.00 -0.19 0.41
... 
...

S 行并不总是存在,但总是以 S 开头。

我喜欢拆分它并创建一个字典,其中仅包含第一个字段(AFA、KTE ...)的键,但也保留“S 2 50.60 ... 0.31”部分作为前一个键的键值,无论何时它们存在。 (也就是将 S 行与上一行合并)。

到目前为止,我做到了:

import collections
st = {} 
with open("file.txt") as f:
    for line in f:
        if len(line.split())==17 or len(line.split())==8 :
            key, value = line.split(None, 1)
            st[key] = (value.split())
            #order output as the order in file
            st=collections.OrderedDict(st)
            print ([key] ,[value])  

但这给了我:

['AFA'] ['MT 0 0  1.22 259 169 FOD 0 50.01 1.3  1.370  0.00  -0.02  1.78 0  0.0']
                    ['S'] ['2 50.620 1.960 2.452 0.00 -0.49 0.31']
['MKE'] ['MS 0 0  4.22 256 149 MDO 1 30.00 1.4  2.370  3.00  -0.52  4.82 0 0.0']
['KTE'] ['KL 0 0  1.22 259 169 FID 0 10.01 2.0  2.470  1.00  -0.12  0.78 1  1.0']
                    ['S'] ['3 70.610 1.960 2.52 0.00 -0.19 0.41']

当我尝试并想要得到:

['AFA'] ['MT 0 0  1.22 259 169 FOD 0 50.01 1.3  1.370  0.00  -0.02  1.78 0  0.0 S 2 50.620 1.960 2.452 0.00 -0.49 0.31']
['MKE'] ['MS 0 0  4.22 256 149 MDO 1 30.00 1.4  2.370  3.00  -0.52  4.82 0 0.0']
['KTE'] ['KL 0 0  1.22 259 169 FID 0 10.01 2.0  2.470  1.00  -0.12  0.78 1  1.0 S 3 70.610 1.960 2.52 0.00 -0.19 0.41']

【问题讨论】:

    标签: python dictionary split lines


    【解决方案1】:

    你可以使用的逻辑是:

    • 记住你读过的最后一个非 S 行
    • 如果您阅读了 S 行,请将其添加到记住的非 S 行并将其放入字典中,然后忘记记住的非 S 行
    • 如果您阅读了非 S 行,请将任何记住的非 S 行放入您的字典中,并改为记住新行
    • 完成文件后,将任何记住的非 S 行放入字典中

    这似乎可以满足您的需求,而无需对您的尝试进行太多修改:

    import pprint
    st = {} 
    with open("file.txt") as f: 
        for line in f: 
            if len(line.split())==17 : 
                key, value = line.split(None, 1) 
                st[key] = (value.split()) 
            elif len(line.split())==8 : 
                st[key] += line.split()
    pprint.pprint(st)
    

    【讨论】:

    • 谢谢你的回复和一年的时间,但问题是我尝试但做不到
    • 如果你展示了你的尝试,有人可以帮助你解决它。
    • import collections st = {} with open("file.txt") as f: head_lines = 4 for line in f: if len(line.split())==17 : key, value = line.split(None, 1) st[key] = (value.split()) elif len(line.split())==8 : st[key] = line; #order output as the order in file st=collections.OrderedDict(st) print ([key] ,[value])
    • 非常感谢!享受周末
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2020-06-20
    • 1970-01-01
    • 2016-03-09
    相关资源
    最近更新 更多