При попытке построить синтаксический анализатор в Python я столкнулся с проблемой для определенной части файла - PullRequest
0 голосов
/ 04 марта 2020

Может кто-нибудь, пожалуйста, помогите в решении проблемы. Мой парсер может прочитать файл только до указанной точки c (только до 'E CC Неисправимые ошибки') в моем случае. Часть ниже, которая не анализируется. Может ли кто-нибудь предложить изменение в моем запросе, чтобы также можно было проанализировать «Тест» и «Последние 10 ошибок». Прикрепление запроса и снимок экрана файла.

from bs4 import BeautifulSoup


def memtest_parser(buf):
    """
    Parser for Memtest logs in html format. This parser parses html output.

    Args:
        buff                    : String         : Buffer containing memtest logs.

   Returns:
        mem_parser_output       : Dictionary     : Dictionary for memtest logs with key and values store unicode string.
                                                   e.g . {u'Summary': {u'Report Date': u'2018-11-05 06:26:20',
                                                          u'Generated by': u'MemTest86 V7.5 Free (64-bit)'}}
    Raises:
        None
    """
    soup = BeautifulSoup(buf, 'html.parser')
    cpu_model = ''
    headers = []
    for header in soup.find_all('h2'):
        headers.append((header.text))
    headers.pop()
    headers.append(u"Result Summary Detail")
    mem_parser_output = defaultdict(lambda: defaultdict(dict))
    tables = soup.findAll("table")[1:5]
    temp = ''
    mem_flg = 0
    test_flg = 0
    internal_headers = ['System', 'BIOS', 'Baseboard', 'CPU Type', 'Memory']
    for ind, table in enumerate(tables):
        rows = table.findAll('tr')
        temp_store = {}
        tests_details = defaultdict(lambda: defaultdict(dict))
        for row in rows:
            cells = row.findAll('td')
            cells_0 = (cells[0].text.strip())
            cells_1 = (cells[1].text.strip())
            if len(cells) == 3:
                test_flg = 1
                cells_2 = (cells[2].text.strip())

            if cells_0 == "CPU Type":
                temp = "CPU Type"
                cpu_model = cells_1
                continue

            if cells_1 != '':
                if mem_flg and cells_0 != '':
                    mem_prev_key = cells_0
                    temp_store.setdefault(mem_prev_key, [])
                    temp_store[mem_prev_key].append(cells_1)
                if headers[ind] == 'System Information' and cells_0 == 'Memory':
                    temp = 'Memory'
                    mem_flg = 1
                    continue
                if temp:
                    if cells_0 == '':
                        temp_store[mem_prev_key].append(cells_1)
                    else:
                        mem_parser_output[headers[ind]
                                          ][temp][cells_0] = cells_1
                else:
                    if test_flg:
                        if cells_0 != "Test":
                            tests_details[cells_0]["Test Passed"] = cells_1
                            tests_details[cells_0]["Errors"] = cells_2
                    else:
                        mem_parser_output[headers[ind]][cells_0] = cells_1

            else:
                if headers[ind] == 'System Information':
                    if cells_0 in internal_headers:
                        temp = cells_0
                else:
                    temp = cells_0

        temp = ''
        if mem_flg:
            mem_parser_output[headers[ind]]["Memory"] = temp_store
            mem_flg = 0
        if test_flg:
            mem_parser_output[headers[ind]] = tests_details
            test_flg = 0
        mem_prev_key = ''
    mem_parser_output['System Information']["CPU Type"]["CPU_Model"] = cpu_model if cpu_model is not '' else "NULL"
    return (default_to_regular(mem_parser_output))

from collections import defaultdict


def default_to_regular(d):
    """
    Convert the default dictionary to regular dictionary

    Args:
        d    : Dictionary    : Dictionary of type 'defaultdict'

    Returns:
        d    : Dictionary    : Dictionary of the type 'dict'

    Raises:
        None
    """
    if isinstance(d, defaultdict):
        d = {k: default_to_regular(v) for k, v in d.iteritems()}
        return d
    else:
        return d


File Screenshot

...