извлечение имени и возраста из текстового файла - PullRequest
0 голосов
/ 11 июня 2018

У меня есть файл .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 из вышеприведенного предложения, которое мне не нужно.Я только хочу извлечь имена людей и их возраст.Я хочу знать, какой должен быть подход?Буду признателен за любую помощь.

1 Ответ

0 голосов
/ 12 июня 2018

Пожалуйста, ознакомьтесь с 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.')
...