Разбор разнородных данных из текстового файла в Python - PullRequest
0 голосов
/ 28 апреля 2020

Я пытаюсь разобрать результаты необработанных данных из текстового файла в организованный кортеж, но не могу понять, как это правильно.

Мои необработанные данные из текстового файла выглядят примерно так:

 Episode Cumulative Results       
EpisodeXD0281119
Date collected21/10/2019
Time collected10:00

 Real time PCR for M. tuberculosis (Xpert MTB/Rif Ultra):
       PCR result                         Mycobacterium tuberculosis complex NOT detected

 Bacterial Culture:
 Bottle: Type                       FAN Aerobic Plus
       Result                             No growth after 5 days


EpisodeST32423457
Date collected23/02/2019
Time collected09:00

 Gram Stain:
       Neutrophils                        Occasional
       Gram positive bacilli              Moderate (2+)
       Gram negative bacilli              Numerous (3+)
       Gram negative cocci                Moderate (2+)


EpisodeST23423457
Date collected23/02/2019
Time collected09:00

 Bacterial Culture:
       A heavy growth of
 1) Klebsiella pneumoniae subsp pneumoniae (KLEPP)
                 ensure that this organism does not spread in the ward/unit.

       A heavy growth of
 2) Enterococcus species (ENCSP)


            Antibiotic/Culture KLEPP  ENCSP

            Trimethoprim-sulfam  R
            Ampicillin / Amoxic  R      S
            Amoxicillin-clavula  R
            Ciprofloxacin        R
            Cefuroxime (Parente  R
            Cefuroxime (Oral)    R
            Cefotaxime / Ceftri  R
            Ceftazidime          R
            Cefepime             R
            Gentamicin           S
            Piperacillin/tazoba  R
            Ertapenem            R
            Imipenem             S
            Meropenem            R

            S - Sensitive ; I - Intermediate ; R - Resistant ; SDD - Sensitive Dose Dependant
            Comment for organism KLEPP:
            ** Please note: this is a carbapenem-RESISTANT organism. Although some
            carbapenems may appear susceptible in vitro, these agents should NOT be used as
            MONOTHERAPY in the treatment of this patient. **

            Please isolate this patient and practice strict contact precautions. Please
            inform Infection Prevention and Control as contact screening might be
            indicated.

            For further advice on the treatment of this isolate, please contact.


            The currently available laboratory methods for performing colistin
            susceptibility results are unreliable and may not predict clinical outcome.
            Based on published data and clinical experience, colistin is a suitable
            therapeutic alternative for carbapenem resistant Acinetobacter spp, as well as
            carbapenem resistant Enterobacteriaceae. If colistin is clinically indicated,
            please carefully assess clinical response.


EpisodeST234234057
Date collected23/02/2019
Time collected09:00

            Authorised by xxxx  on 27/02/2019  at 10:35

 MIC by E-test:
 Organism                           Klebsiella pneumoniae (KLEPN)
       Antibiotic                         Meropenem
       MIC corrected                      4 ug/mL
       MIC interpretation                 Resistant
       Antibiotic                         Imipenem
       MIC corrected                      1 ug/mL
       MIC interpretation                 Sensitive
       Antibiotic                         Ertapenem
       MIC corrected                      2 ug/mL
       MIC interpretation                 Resistant


EpisodeST23423493
Date collected18/02/2019
Time collected03:15

       Potassium                               4.4      mmol/L                   3.5 - 5.1

EpisodeST45445293
Date collected18/02/2019
Time collected03:15

       Creatinine         32 L    umol/L                    49 - 90
       eGFR (MDRD formula)                     >60      mL/min/1.73 m2

       Creatinine         28 L    umol/L                    49 - 90
       eGFR (MDRD formula)                     >60      mL/min/1.73 m2

По сути, паттерн состоит в том, что ВСЕ данные начинаются с уникального НОМЕРА ЭПИЗОДА, а затем - ДАТА и ВРЕМЯ, а затем результат любого теста. Это шаблон во всем. То, что я пытаюсь проанализировать в своем кортеже, это дата , время , название теста и результат - что бы это ни могло быть. У меня есть следующий код:

with open(filename) as f:
    data = f.read()

data = data.splitlines()

DS = namedtuple('DS', 'date time name value')
parsed = list()
idx_date = [i for i, r in enumerate(data) if r.strip().startswith('Date')]

for start, stop in zip(idx_date[:-1], idx_date[1:]):
    chunk = data[start:stop]
    date = time = name = value = None
    for row in chunk:
        if not row: continue
        row = row.strip()
        if row.startswith('Episode'): continue
        if row.startswith('Date'):
            _, date = row.split()
            date = date.replace('collected', '')
        elif row.startswith('Time'):
            _, time = row.split()
            time = time.replace('collected', '')
        else:
            name, value, *_ = row.split()
        print (name)
    parsed.append(DS(date, time, name, value))

print(parsed)

Моя ошибка в том, что я не могу найти способ для анализа неоднородности теста RESULT таким образом, чтобы я мог использовать позже, например, для кортежа DS ( 'DS', 'значение имени даты-времени'):

DATE = 21/10/2019  
TIME = 10:00  
NAME = Real time PCR for M tuberculosis or Potassium 
RESULT = Negative or 4.7

Любой совет приветствуется. Я ударил кирпичную стену.

...