Se usó la API de Cloud Translation para traducir esta página.
Switch to English

Inspecciona texto estructurado en busca de datos sensibles

Cloud Data Loss Prevention (DLP) puede detectar y clasificar datos sensibles en el contenido estructurado, como CSV. Mediante la inspección o la desidentificación como una tabla, la estructura y las columnas proporcionan pistas adicionales a Cloud DLP. Es posible que estas pistas le permitan brindar mejores resultados para algunos casos prácticos.

Inspecciona una tabla

Las muestras de códigos que figuran a continuación ilustran cómo inspeccionar una tabla de datos en busca de contenido confidencial. Las tablas son compatibles con una variedad de tipos.


Para obtener más información sobre cómo usar la API de Cloud DLP con JSON, consulta la guía de inicio rápido de JSON.

Entrada de JSON:


      "headers": [{"name":"name"}, {"name":"phone"}],
      "rows": [{
          {"string_value": "John Doe"},
          {"string_value": "(206) 555-0123"}

Salida de JSON:

  "result": {
    "findings": [
      "quote": "(206) 555-0123",
      "infoType": {
       "name": "PHONE_NUMBER"
      "likelihood": "VERY_LIKELY",
      "location": {
         "byteRange": {
          "end": "14"
         "codepointRange": {
          "end": "14"
         "contentLocations": [
           "recordLocation": {
              "fieldId": {
               "name": "phone"
              "tableLocation": {
      "createTime": "2019-03-08T23:55:10.980Z"


Si deseas obtener información para instalar y usar la biblioteca cliente de Cloud DLP, consulta las Bibliotecas cliente de Cloud DLP.


public class InspectTable {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    Table tableToInspect =
                    .addValues(Value.newBuilder().setStringValue("John Doe").build())
                    .addValues(Value.newBuilder().setStringValue("(206) 555-0123").build()))

    inspectTable(projectId, tableToInspect);

  // Inspects the provided text.
  public static void inspectTable(String projectId, Table tableToInspect) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify the table to be inspected.
      ContentItem item = ContentItem.newBuilder().setTable(tableToInspect).build();

      // Specify the type of info the inspection will look for.
      // See for complete list of info types
      InfoType infoType = InfoType.newBuilder().setName("PHONE_NUMBER").build();

      // Construct the configuration for the Inspect request.
      InspectConfig config =

      // Construct the Inspect request to be sent by the client.
      InspectContentRequest request =
              .setParent(LocationName.of(projectId, "global").toString())

      // Use the client to send the API request.
      InspectContentResponse response = dlp.inspectContent(request);

      // Parse the response and process results
      System.out.println("Findings: " + response.getResult().getFindingsCount());
      for (Finding f : response.getResult().getFindingsList()) {
        System.out.println("\tQuote: " + f.getQuote());
        System.out.println("\tInfo type: " + f.getInfoType().getName());
        System.out.println("\tLikelihood: " + f.getLikelihood());
    } catch (Exception e) {
      System.out.println("Error during inspectString: \n" + e.toString());


Si deseas obtener información para instalar y usar la biblioteca cliente de Cloud DLP, consulta las Bibliotecas cliente de Cloud DLP.

def inspect_table(
    """Uses the Data Loss Prevention API to analyze strings for protected data.
        project: The Google Cloud project id to use as a parent resource.
        data: Json string representing table data.
        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',
        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.
        None; the response from the API is printed to the terminal.
        data = {
                "phone number"

        >> $ python table \
        '{"header": ["email", "phone number"],
        "rows": [["", "4232342345"],
        ["", "4253458383"]]}'
        >>  Quote:
            Info type: EMAIL_ADDRESS
            Likelihood: 4
            Info type: EMAIL_ADDRESS
            Likelihood: 4

    # Import the client library.

    # Instantiate a client.
    dlp =

    # 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]

    # Prepare custom_info_types by parsing the dictionary word lists and
    # regex patterns.
    if custom_dictionaries is None:
        custom_dictionaries = []
    dictionaries = [
            "info_type": {"name": "CUSTOM_DICTIONARY_{}".format(i)},
            "dictionary": {"word_list": {"words": custom_dict.split(",")}},
        for i, custom_dict in enumerate(custom_dictionaries)
    if custom_regexes is None:
        custom_regexes = []
    regexes = [
            "info_type": {"name": "CUSTOM_REGEX_{}".format(i)},
            "regex": {"pattern": custom_regex},
        for i, custom_regex in enumerate(custom_regexes)
    custom_info_types = dictionaries + regexes

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

    # Construct the `table`. For more details on the table schema, please see
    headers = [{"name": val} for val in data["header"]]
    rows = []
    for row in data["rows"]:
        rows.append({"values": [{"string_value": cell_val} for cell_val in row]})

    table = {}
    table["headers"] = headers
    table["rows"] = rows
    item = {"table": table}
    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.inspect_content(
        request={"parent": parent, "inspect_config": inspect_config, "item": item}

    # Print out the results.
    if response.result.findings:
        for finding in response.result.findings:
                if finding.quote:
                    print("Quote: {}".format(finding.quote))
            except AttributeError:
            print("Info type: {}".format(
            print("Likelihood: {}".format(finding.likelihood))
        print("No findings.")

Texto en comparación con texto estructurado

La estructuración del texto puede ayudar a proporcionar contexto. Si se inspecciona la misma solicitud del ejemplo anterior como una string, es decir, como “John Doe, (206) 555-0123”, proporcionaría resultados menos precisos. Esto se debe a que Cloud DLP tiene menos pistas contextuales sobre cuál podría ser el propósito del número. Cuando sea posible, considera analizar tus strings en un objeto de tabla para obtener resultados de análisis más precisos.