如何从txt文档中提取信息

8iwquhpp  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(497)

我这里有原始文本:

IR DATA - TIME IN NAV = 40 MINUTES 

    NAME  LABEL    DATA                     DECODED MESSAGE
    ----- -----    ----------               ----------------------------------
    LATIT (310)    X'E4554813'              48.747711
    LONGI (311)    X'E036ED93'              2.413731
    GNDSP (312)    X'E0008153'              0.500000
    TRHDG (314)    X'7400B933'              -134.972534
    PITCH (324)    X'E000352B'              0.005493
    ROLL  (325)    X'7FFE55AB'              -0.076904
    N-VEL (366)    X'E000216F'              0.125000
    E-VEL (367)    X'60007DEF'              0.375000
    FAULT (270)    X'0008111D'
                                            IN NAV MODE            
                                            DC FAIL-ON DC {FAIL WHILE ON DC}
    MAINT (350)    X'00000D17'

 IR DATA - TIME IN NAV = 45 MINUTES 

    NAME  LABEL    DATA                     DECODED MESSAGE
    ----- -----    ----------               ----------------------------------
    LATIT (310)    X'64554613'              48.747368
    LONGI (311)    X'E036F093'              2.414246
    GNDSP (312)    X'6000AD53'              0.625000
    TRHDG (314)    X'7400B933'              -134.972534
    PITCH (324)    X'E000352B'              0.005493
    ROLL  (325)    X'7FFE55AB'              -0.076904
    N-VEL (366)    X'FFFF516F'              -0.750000
    E-VEL (367)    X'E00001EF'              0.000000
    FAULT (270)    X'0008111D'
                                            IN NAV MODE            
                                            DC FAIL-ON DC {FAIL WHILE ON DC}
    MAINT (350)    X'00000D17'

我想从两个不同的列表中提取:

在提取这些信息(大约有10个)后,我将制作一个图表,使结果更直观,如:

我想知道如何提取这些数据,特别是。

0ve6wy6x

0ve6wy6x1#

你可以用 re 任务模块:

import re

with open("your_file.txt", "r") as f_in:
    text = f_in.read()

list1 = list(
    map(float, re.findall(r"N-VEL.*?([\d\.-]+)\s*$", text, flags=re.M))
)
list2 = list(
    map(float, re.findall(r"E-VEL.*?([\d\.-]+)\s*$", text, flags=re.M))
)

print(list1)
print(list2)

印刷品:

[0.125, -0.75]
[0.375, 0.0]
g52tjvyc

g52tjvyc2#

您还可以对文件进行一次迭代,并根据您的条件检查字符串。

from collections import defaultdict

d = defaultdict(list)

with open("foo.txt", "r") as fin:
    for line in fin:
        tmp = line.strip().split()
        try:
            val = tmp[0]
        except IndexError:
            continue
        if val in ("N-VEL", "E-VEL"):
            d[val].append(float(tmp[-1]))
        else:
            continue

print(d)
>> defaultdict(list, {'N-VEL': [0.125, -0.75], 'E-VEL': [0.375, 0.0]})

相关问题