получение имени и возраста из текстового файла

У меня есть файл .txt, из которого я должен получить имя и возраст. Файл .txt содержит данные в следующем формате:

Age: 71 . John is 47 years old. Sam; Born: 05/04/1989(29).
Kenner is a patient Age: 36 yrs    Height: 5 feet 1 inch; weight is 56 kgs. 
This medical record is 10 years old. 

Output 1: John, Sam, Kenner
Output_2: 47, 29, 36  

Я использую регулярное выражение для извлечения данных. Например, для возраста я использую следующие регулярные выражения:

re.compile(r'age:\s*\d{1,3}',re.I)

re.compile(r'(age:|is|age|a|) \s*\d{1,3}(\s|y)',re.I)

re.compile(r'.* Age\s*:*\s*[0-9]+.*',re.I)

re.compile(r'.* [0-9]+ (?:year|years|yrs|yr) \s*',re.I)

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

This medical record is 10 years old.

Я получаю «10» из приведенного выше предложения, которое мне не нужно. Я только хочу извлечь имена людей и их возраст. Я хочу знать, какой должен быть подход? Буду признателен за любую помощь.


person bisht    schedule 11.06.2018    source источник
comment
Вы не можете сделать это таким образом. Чтобы это работало, вы должны точно знать, что такое форма для ИМЯ и ВОЗРАСТ, и должны иметь отношение 1 к 1.   -  person    schedule 11.06.2018
comment
@sln Спасибо за помощь. Я понял вашу точку зрения, но данные случайны, поскольку вы можете видеть, что в документе нет уникального формата. У меня не может быть отношений 1 на 1. Я хочу знать, есть ли какой-либо другой подход, такой как обработка естественного языка или какой-то другой?   -  person bisht    schedule 11.06.2018


Ответы (1)


Ознакомьтесь с API предотвращения потери данных в облаке. Вот репозиторий GitHub с примерами. Это то, что вы, вероятно, захотите.

def inspect_string(project, content_string, info_types,
                   min_likelihood=None, max_findings=None, include_quote=True):
    """Uses the Data Loss Prevention API to analyze strings for protected data.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        content_string: The string to inspect.
        info_types: A list of strings representing info types to look for.
            A full list of info type categories can be fetched from the API.
        min_likelihood: A string representing the minimum likelihood threshold
            that constitutes a match. One of: 'LIKELIHOOD_UNSPECIFIED',
            'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY'.
        max_findings: The maximum number of findings to report; 0 = no maximum.
        include_quote: Boolean for whether to display a quote of the detected
            information in the results.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Import the client library.
    import google.cloud.dlp

    # Instantiate a client.
    dlp = google.cloud.dlp.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries (protos are also accepted).
    info_types = [{'name': info_type} for info_type in info_types]

    # Construct the configuration dictionary. Keys which are None may
    # optionally be omitted entirely.
    inspect_config = {
        'info_types': info_types,
        'min_likelihood': min_likelihood,
        'include_quote': include_quote,
        'limits': {'max_findings_per_request': max_findings},
      }

    # Construct the `item`.
    item = {'value': content_string}

    # Convert the project id into a full resource id.
    parent = dlp.project_path(project)

    # Call the API.
    response = dlp.inspect_content(parent, inspect_config, item)

    # Print out the results.
    if response.result.findings:
        for finding in response.result.findings:
            try:
                if finding.quote:
                    print('Quote: {}'.format(finding.quote))
            except AttributeError:
                pass
            print('Info type: {}'.format(finding.info_type.name))
            print('Likelihood: {}'.format(finding.likelihood))
    else:
        print('No findings.')
person Torry Yang    schedule 11.06.2018
comment
Спасибо вам за помощь. Да, DLP был бы очень полезен. Я буду читать больше об этом. В моем случае метки типа Имя: Возраст: не везде упоминаются, так что, возможно, там это не сработает. - person bisht; 12.06.2018
comment
Что я придумал для решения этой проблемы: в Интернете доступен текстовый файл, содержащий 90 тыс. имен. Я сделаю поиск между моими файлами и этим файлом, чтобы проверить все имена. - person bisht; 12.06.2018
comment
DLP делает имена и возраст. Вот список всех обнаруженных InfoType: cloud.google.com/dlp/ документы/справочник по типам информации - person Torry Yang; 12.06.2018
comment
Можно ли связаться с вами по электронной почте или через LinkedIn? - person bisht; 12.06.2018