Conversión de formato de conjunto de datos NER general a formato JSON Daquan

prefacio

Recientemente, estoy realizando tareas relacionadas con la extracción general de modelos grandes, es necesario convertir todos los conjuntos de datos al mismo formato para facilitar la construcción de conjuntos de datos de ajuste fino de instrucciones. Al procesar datos, es necesario convertir conjuntos de datos NER en diferentes formatos en datos de formato json fáciles de manejar, lo cual es una tarea muy complicada. En el campo de NER, no existe una especificación de formato unificado. El bloguero recopiló casi 30 conjuntos de datos de NER y concluyó que los formatos comunes de conjuntos de datos de NER incluyen BIO, BIEO, BIO en formato Excel, separación de etiquetas de datos, json incrustado, etc. ser dos o tres conjuntos de datos en cada formato, y codificarlos individualmente requeriría mucho esfuerzo y ralentizaría el trabajo. Aunque hay muchos conjuntos de datos de fuente abierta que se han procesado en formato json en github, esto no cubre todos los conjuntos de datos NER. Es mejor enseñar a las personas a pescar que enseñarles a pescar. Este artículo resumirá el conjunto de datos comunes. formatos en el campo NER. Y proporcione el código para convertir el conjunto de datos en formato json para que los lectores lo recojan. Además, el conjunto de datos procesados ​​se puede descargar aquí . Si le resulta útil, por favor, dele me gusta y anime al bloguero~


1. Descripción general de los conjuntos de datos NER

Hay muchos tipos de conjuntos de datos en el dominio NER, y los formatos de conjuntos de datos comunes se muestran en la siguiente tabla:
inserte la descripción de la imagen aquí

Aquí primero analizo los pros y los contras de los diferentes formatos de conjuntos de datos y por qué elijo el formato json.

1.1 json integrado

El primero es el conjunto de datos representativo de Boson-NER con json incrustado, y la información de la entidad está marcada en el texto. Aunque el tipo de entidad es muy claro, pero la información de ubicación no está marcada, y para una muestra, es imposible saberlo. cuántos tipos de entidad hay, y es difícil de obtener directamente.

1.2 BIOGRAFÍA

Los tipos de BIO se pueden subdividir aún más. Uno es que en un archivo txt, solo hay un token en una línea, y un token va seguido de su tipo. El contenido general debe leerse verticalmente. La otra forma se basa en el texto original después de cada token Junto con los tipos de entidad, estos tipos son más fáciles de leer, pero más complicados de manejar.

1.3 JSON en capas

El formato json jerárquico está más en línea con el formato final que debe procesarse de manera uniforme. Cada muestra está anidada por un par de llaves, que incluye el contenido del texto y el contenido de la etiqueta, pero la información de la etiqueta, la mención y la ubicación están anidadas en la capa. por capa, lo cual es inconveniente de extraer.

1.4 BIEO

El formato de BIEO es similar al formato de BIO, excepto que hay un símbolo especial adicional de fin y los caracteres especiales deben considerarse por separado al procesar.

1.5 Separación de etiquetas de datos

El formato de datos con separación de etiquetas de datos es el peor, no puede ver directamente la entidad ni obtener la información de la ubicación de la entidad, pero su ventaja es que es más conveniente de manejar, solo necesita comparar las ubicaciones correspondientes de los dos archivos para extraer la entidad correspondiente y la información de ubicación.

1.6 json estándar

El estándar aquí es el tipo de formato de datos json al que eventualmente convertiré. Tome la siguiente muestra de datos como ejemplo: puede
inserte la descripción de la imagen aquí
ver que cada muestra incluye una colección de oraciones y entidades, la oración es el contenido de la muestra y la colección de entidades contiene el mención de cada entidad, tipo e información de ubicación, este formato de datos es el formato que creo que se procesa mejor, y también es el formato procesado por el código en este blog.

2. BIO_a_JSON

Tipo de dato primitivo:

相 O
比 O
之 O
下 O
, O
青 B-ORG
岛 I-ORG
海 I-ORG
牛 I-ORG
队 I-ORG
和 O
广 B-ORG
州 I-ORG
松 I-ORG
日 I-ORG
队 I-ORG
的 O
雨 O
中 O
之 O
战 O
虽 O
然 O
也 O
是 O
0 O
∶ O
0 O
, O
但 O
乏 O
善 O
可 O
陈 O
。 O

código:

import json
import sys
import os
sys.path.append("..")

def bio_to_json(input_files, output_files, label_output_file):
    label_set = set()

    for input_file, output_file in zip(input_files, output_files):
        data = []
        with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()
            sentence = ""
            entities = []
            entity_name = ""
            entity_type = ""
            start_position = 0
            for line in lines:
                if line == '\n':
                    # if there's an entity already being processed, append it to entities
                    if entity_name:
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    # append the processed sentence to data
                    data.append({
    
    'sentence': sentence, 'entities': entities})
                    sentence = ""
                    entities = []
                else:
                    print(line)
                    word, tag = line.rstrip('\n').split('	')
                    if tag.startswith('B'):
                        # if there's an entity already being processed, append it to entities
                        if entity_name:
                            entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = word
                        entity_type = tag.split('-')[1]
                        label_set.add(entity_type)  # add this entity type to the set
                        start_position = len(sentence)
                    elif tag.startswith('I'):
                        entity_name += word
                    else:
                        # if there's an entity already being processed, append it to entities
                        if entity_name:
                            entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    sentence += word
            # for the last entity of the last sentence
            if entity_name:
                entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
            if sentence:
                data.append({
    
    'sentence': sentence, 'entities': entities})

        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

    with open(label_output_file, 'w', encoding='utf-8') as f:
        json.dump(list(label_set), f, ensure_ascii=False, indent=4)



currPath = os.path.join("datasets", "Weibo")
input_files = [os.path.join(currPath, "train.txt"), os.path.join(currPath, "test.txt"), os.path.join(currPath, "dev.txt")]
output_files = [os.path.join(currPath, "train.json"), os.path.join(currPath, "test.json"), os.path.join(currPath, "dev.json")]
label_output_file = os.path.join(currPath, "label.json")
bio_to_json(input_files, output_files, label_output_file)

Generar formato json:

{
    
    
    "sentence": "相比之下,青岛海牛队和广州松日队的雨中之战虽然也是0∶0,但乏善可陈。",
    "entities": [
        {
    
    
            "name": "青岛海牛队",
            "type": "机构",
            "pos": [
                5,
                10
            ]
        },
        {
    
    
            "name": "广州松日队",
            "type": "机构",
            "pos": [
                11,
                16
            ]
        }
    ]
},

3. BIEO_a_JSON

Tipo de dato primitivo:

中 B-GPE
国 E-GPE
将 O
加 O
快 O
人 O
才 O
市 O
场 O
体 O
系 O
建 O
设 O

código:

      
import json

def bieo_to_json(input_files, output_files, label_output_file):
    num = 0

    label_set = set()

    for input_file, output_file in zip(input_files, output_files):
        data = []
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            sentence = ""
            entities = []
            entity_name = ""
            entity_type = ""
            start_position = 0
            for line in lines:
                if line == '\n':
                    # if there's an entity already being processed, append it to entities
                    if entity_name:
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    # append the processed sentence to data
                    data.append({
    
    'sentence': sentence, 'entities': entities})
                    num += 1
                    sentence = ""
                    entities = []
                else:
                    word, mid, tag = line.rstrip('\n').split('	')
                    if tag.startswith('B'):
                        entity_name = word
                        entity_type = tag.split('-')[1]
                        label_set.add(entity_type)  # add this entity type to the set
                        start_position = len(sentence)
                    elif tag.startswith('I'):
                        entity_name += word
                    elif tag.startswith('E'):
                        entity_name += word
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    elif tag.startswith('S'):
                        entity_name = word
                        entity_type = tag.split('-')[1]
                        label_set.add(entity_type)  # add this entity type to the set
                        start_position = len(sentence)
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    else:
                        # if there's an entity already being processed, append it to entities
                        if entity_name:
                            entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    sentence += word
            # for the last entity of the last sentence
            if entity_name:
                entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
            if sentence:
                data.append({
    
    'sentence': sentence, 'entities': entities})
                num += 1

        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

    with open(label_output_file, 'w', encoding='utf-8') as f:
        json.dump(list(label_set), f, ensure_ascii=False, indent=4)

    print(num)


import sys
import os
sys.path.append("..")


currPath = os.path.join( "datasets", "CCKS2017-NER")
input_files = [os.path.join(currPath, "train.txt"), os.path.join(currPath, "test.txt")]
output_files = [os.path.join(currPath, "train.json"), os.path.join(currPath, "test.json")]
label_output_file = os.path.join(currPath, "label.json")
bieo_to_json(input_files, output_files, label_output_file)
    

Generar formato json:

{
    
    
    "sentence": "中国将加快人才市场体系建设。",
    "entities": [
        {
    
    
            "name": "中国",
            "type": "国家",
            "pos": [
                0,
                2
            ]
        }
    ]
},

4. BMEO_a_JSON

Tipo de dato primitivo:

高 B-NAME
勇 E-NAME
: O
男 O
, O
中 B-CONT
国 M-CONT
国 M-CONT
籍 E-CONT
, O
无 O
境 O
外 O
居 O
留 O
权 O
, O

código:

      
import json
import sys
import os
sys.path.append("..")

def bmeo_to_json(input_files, output_files, label_output_file):
    label_set = set()

    for input_file, output_file in zip(input_files, output_files):
        data = []
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            sentence = ""
            entities = []
            entity_name = ""
            entity_type = ""
            start_position = 0
            for line in lines:
                if line == '\n':
                    # if there's an entity already being processed, append it to entities
                    if entity_name:
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    # append the processed sentence to data
                    data.append({
    
    'sentence': sentence, 'entities': entities})
                    sentence = ""
                    entities = []
                else:
                    word, tag = line.rstrip('\n').split(' ')
                    if tag.startswith('B'):
                        entity_name = word
                        entity_type = tag.split('-')[1]
                        label_set.add(entity_type)  # add this entity type to the set
                        start_position = len(sentence)
                    elif tag.startswith('M'):
                        entity_name += word
                    elif tag.startswith('E'):
                        entity_name += word
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    elif tag.startswith('S'):
                        entity_name = word
                        entity_type = tag.split('-')[1]
                        label_set.add(entity_type)  # add this entity type to the set
                        start_position = len(sentence)
                        entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    else:
                        # if there's an entity already being processed, append it to entities
                        if entity_name:
                            entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
                        entity_name = ""
                        entity_type = ""
                    sentence += word
            # for the last entity of the last sentence
            if entity_name:
                entities.append({
    
    'name': entity_name, 'type': entity_type, 'pos': [start_position, start_position + len(entity_name)]})
            if sentence:
                data.append({
    
    'sentence': sentence, 'entities': entities})

        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)

    with open(label_output_file, 'w', encoding='utf-8') as f:
        json.dump(list(label_set), f, ensure_ascii=False, indent=4)


currPath = os.path.join( "datasets", "简历-NER")
input_files = [os.path.join(currPath, "train.txt"), os.path.join(currPath, "test.txt"), os.path.join(currPath, "dev.txt")]
output_files = [os.path.join(currPath, "train.json"), os.path.join(currPath, "test.json"), os.path.join(currPath, "dev.json")]
label_output_file = os.path.join(currPath, "label.json")
bmeo_to_json(input_files, output_files, label_output_file)

    

Generar formato json:

{
    
    
    "sentence": "高勇:男,中国国籍,无境外居留权,",
    "entities": [
        {
    
    
            "name": "高勇",
            "type": "姓名",
            "pos": [
                0,
                2
            ]
        },
        {
    
    
            "name": "中国国籍",
            "type": "国籍",
            "pos": [
                5,
                9
            ]
        }
    ]
},

5.D_BIO_JSON

Tipo de dato primitivo:

交行14年用过,半年准备提额,却直接被降到1K,半年期间只T过一次三千,其它全部真实消费,第六个月的时候为了增加评分提额,还特意分期两万,但降额后电话投诉,申请提...
B-BANK I-BANK O O O O O O O O O O B-COMMENTS_N I-COMMENTS_N O O O O O B-COMMENTS_ADJ I-COMMENTS_ADJ O O O O O O O O O O O O O O O O O O O O O B-COMMENTS_N I-COMMENTS_N O O O O O O O O O O B-COMMENTS_N I-COMMENTS_N O O B-COMMENTS_N I-COMMENTS_N O O O O B-PRODUCT I-PRODUCT O O O O B-COMMENTS_ADJ O O O O O O O O O O O O O

código:

import json
import os
import sys
sys.path.append("..")

def d_bio_to_json(text_file, label_file, output_file, output_label_file):
    with open(text_file, 'r', encoding='utf-8') as f_text, open(label_file, 'r', encoding='utf-8') as f_label:
        texts = f_text.read().splitlines()
        labels = f_label.read().splitlines()
    
    num = 0

    data = []
    label_set = set()
    for text, label in zip(texts, labels):
        entities = []
        entity = None
        start_idx = None

        tokens = text.split()
        tags = label.split()

        for i, (token, tag) in enumerate(zip(tokens, tags)):
            if tag.startswith('B'):
                if entity is not None:
                    entities.append(entity)
                entity = {
    
    
                    "name": token,
                    "type": tag[2:],
                    "pos": [i, i + 1]
                }
                start_idx = i
                label_set.add(tag[2:])
            elif tag.startswith('I'):
                if entity is None:
                    entity = {
    
    
                        "name": token,
                        "type": tag[2:],
                        "pos": [i, i + 1]
                    }
                    start_idx = i
                    label_set.add(tag[2:])
                else:
                    entity["name"] += token
                    entity["pos"][1] = i + 1
            elif tag == 'O':
                if entity is not None:
                    entities.append(entity)
                    entity = None

        if entity is not None:
            entities.append(entity)

        sentence = ''.join(tokens)  # 去除空格
        data.append({
    
    
            "sentence": sentence,
            "entities": entities
        })
        num += 1

    with open(output_file, 'w', encoding='utf-8') as f_out:
        json.dump(data, f_out, ensure_ascii=False, indent=4)

    with open(output_label_file, 'w', encoding='utf-8') as f_label:
        json.dump(list(label_set), f_label, ensure_ascii=False, indent=4)

    print(num)

currPath = os.path.join( "datasets", "人民日报2014")
text_file = os.path.join(currPath, "source.txt")
label_file = os.path.join(currPath, "target.txt")
output_file = os.path.join(currPath, "train.json")
output_label_file = os.path.join(currPath, "label.json")
d_bio_to_json(text_file, label_file, output_file, output_label_file)

Generar formato json:

{
    
    
  "sentence": "交行14年用过,半年准备提额,却直接被降到1K,半年期间只T过一次三千,其它全部真实消费,第六个月的时候为了增加评分提额,还特意分期两万,但降额后电话投诉,申请提...",
  "entities": [
    {
    
    
      "name": "交行",
      "type": "银行",
      "pos": [
        0,
        2
      ]
    },
    {
    
    
      "name": "提额",
      "type": "金融操作",
      "pos": [
        12,
        14
      ]
    },
    {
    
    
      "name": "降到",
      "type": "形容词",
      "pos": [
        19,
        21
      ]
    },
    {
    
    
      "name": "消费",
      "type": "金融操作",
      "pos": [
        42,
        44
      ]
    },
    {
    
    
      "name": "增加",
      "type": "金融操作",
      "pos": [
        54,
        56
      ]
    },
    {
    
    
      "name": "提额",
      "type": "金融操作",
      "pos": [
        58,
        60
      ]
    },
    {
    
    
      "name": "分期",
      "type": "产品",
      "pos": [
        64,
        66
      ]
    },
    {
    
    
      "name": "降",
      "type": "形容词",
      "pos": [
        70,
        71
      ]
    }
  ]
},

6. BIO_JSON_a_JSON

Tipo de dato primitivo:

{
    
    "text": "来一首周华健的花心", "labels": ["O", "O", "O", "B-singer", "I-singer", "I-singer", "O", "B-song", "I-song"]}

código:

import json

def bio_json_to_json(input_file, output_file, label_file):
    num = 0
    label_set = set()
    
    with open(input_file, 'r', encoding='utf-8') as f:
        data = f.read().splitlines()

    converted_data = []

    for sample in data:
        sample = json.loads(sample)
        sentence = sample['text']
        labels = sample['labels']
        entities = []
        entity_name = ""
        entity_start = None
        entity_type = None

        for i, label in enumerate(labels):
            if label.startswith('B-'):
                if entity_name:
                    entities.append({
    
    
                        'name': entity_name,
                        'type': entity_type,
                        'pos': [entity_start, i]
                    })
                    label_set.add(entity_type)
                entity_name = sentence[i]
                entity_start = i
                entity_type = label[2:]
            elif label.startswith('I-'):
                if entity_name:
                    entity_name += sentence[i]
            else:
                if entity_name:
                    entities.append({
    
    
                        'name': entity_name,
                        'type': entity_type,
                        'pos': [entity_start, i]
                    })                    
                    label_set.add(entity_type)
                    entity_name = ""
                    entity_start = None
                    entity_type = None

        if entity_name:
            entities.append({
    
    
                'name': entity_name,
                'type': entity_type,
                'pos': [entity_start, len(labels)]
            })
            label_set.add(entity_type)

        converted_data.append({
    
    
            'sentence': sentence,
            'entities': entities
        })
        num += 1

    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(converted_data, f, ensure_ascii=False, indent=2)
    
    with open(label_file, 'w', encoding='utf-8') as f_label:
        json.dump(list(label_set), f_label, ensure_ascii=False, indent=4)

    

Generar formato json:

{
    
    
  "sentence": "来一首周华健的花心",
  "entities": [
    {
    
    
      "name": "周华健",
      "type": "歌手",
      "pos": [
        3,
        6
      ]
    },
    {
    
    
      "name": "花心",
      "type": "歌曲",
      "pos": [
        7,
        9
      ]
    }
  ]
},

7. JSON_a_JSON

Tipo de dato primitivo:

{
    
     "text": "呼吸肌麻痹和呼吸中枢受累患者因呼吸不畅可并发肺炎、肺不张等。", "entities": [ {
    
     "start_idx": 0, "end_idx": 2, "type": "bod", "entity: "呼吸肌" }, { "start_idx": 0, "end_idx": 4, "type": "sym", "entity: "呼吸肌麻痹" }, {
    
     "start_idx": 6, "end_idx": 9, "type": "bod", "entity: "呼吸中枢" }, { "start_idx": 6, "end_idx": 11, "type": "sym", "entity: "呼吸中枢受累" }, {
    
     "start_idx": 15, "end_idx": 18, "type": "sym", "entity: "呼吸不畅" }, { "start_idx": 22, "end_idx": 23, "type": "dis", "entity: "肺炎" }, {
    
     "start_idx": 25, "end_idx": 27, "type": "dis", "entity: "肺不张" } ] }

código:

import json
import os
import sys
sys.path.append("..")

def json_to_json(input_files, output_files, label_output_file):
    label_set = set()

    for input_file, output_file in zip(input_files, output_files):
        with open(input_file, 'r', encoding='utf-8') as f_in:
            data = json.load(f_in)

        converted_data = []

        for item in data:
            sentence = item['text']
            entities = []

            for entity in item['entities']:
                start_idx = entity['start_idx']
                end_idx = entity['end_idx']
                entity_type = entity['type']
                entity_name = entity['entity']
                entities.append({
    
    
                    'name': entity_name,
                    'type': entity_type,
                    'pos': [start_idx, end_idx]
                })
                label_set.add(entity_type)

            converted_data.append({
    
    
                'sentence': sentence,
                'entities': entities
            })

        with open(output_file, 'w', encoding='utf-8') as f_out:
            json.dump(converted_data, f_out, ensure_ascii=False, indent=4)

    with open(label_output_file, 'w', encoding='utf-8') as f_label:
        json.dump(list(label_set), f_label, ensure_ascii=False, indent=4)



currPath = os.path.join( "datasets", "CMeEE-V2")
input_files = [os.path.join(currPath, "CMeEE-V2_train.json"), os.path.join(currPath, "CMeEE-V2_test.json"), os.path.join(currPath, "CMeEE-V2_dev.json")]
output_files = [os.path.join(currPath, "train.json"), os.path.join(currPath, "test.json"), os.path.join(currPath, "dev.json")]
label_output_file = os.path.join(currPath, "label.json")
json_to_json(input_files, output_files, label_output_file)
 

Generar formato json:

{
    
    
    "sentence": "呼吸肌麻痹和呼吸中枢受累患者因呼吸不畅可并发肺炎、肺不张等。",
    "entities": [
        {
    
    
            "name": "呼吸肌麻痹",
            "type": "疾病",
            "pos": [
                0,
                5
            ]
        },
        {
    
    
            "name": "呼吸中枢",
            "type": "部位",
            "pos": [
                6,
                10
            ]
        },
        {
    
    
            "name": "呼吸中枢受累",
            "type": "症状",
            "pos": [
                6,
                12
            ]
        },
        {
    
    
            "name": "呼吸不畅",
            "type": "症状",
            "pos": [
                15,
                19
            ]
        },
        {
    
    
            "name": "肺炎",
            "type": "疾病",
            "pos": [
                22,
                24
            ]
        },
        {
    
    
            "name": "肺不张",
            "type": "疾病",
            "pos": [
                25,
                28
            ]
        }
    ]
},

8. JSON_a_JSON

Tipo de dato primitivo:

{
    
    "text": "生生不息CSOL生化狂潮让你填弹狂扫", "label": {
    
    "game": {
    
    "CSOL": [[4, 7]]}}}

código:

      
import json

def nested_json_to_json(input_files, output_files, label_output_file):
    num = 0
    label_set = set()

    for input_file, output_file in zip(input_files, output_files):
        with open(input_file, 'r', encoding='utf-8') as f_in:
            data = f_in.read().splitlines()


        converted_data = []

        for item in data:
            item = json.loads(item)
            sentence = item['text']
            entities = []

            for label, entity in item['label'].items():
                entity_type = label
                entity_name = list(entity.keys())[0]
                start_idx = list(entity.values())[0][0][0]
                end_idx = list(entity.values())[0][0][1]
                entities.append({
    
    
                    'name': entity_name,
                    'type': entity_type,
                    'pos': [start_idx, end_idx]
                })
                label_set.add(entity_type)

            converted_data.append({
    
    
                'sentence': sentence,
                'entities': entities
            })
            num += 1

        with open(output_file, 'w', encoding='utf-8') as f_out:
            json.dump(converted_data, f_out, ensure_ascii=False, indent=4)

    with open(label_output_file, 'w', encoding='utf-8') as f_label:
        json.dump(list(label_set), f_label, ensure_ascii=False, indent=4)

    print(num)



import os
import sys
sys.path.append("..")

currPath = os.path.join( "datasets", "CLUENER")
input_files = [os.path.join(currPath, "CLUENER_train.json"),os.path.join(currPath, "CLUENER_dev.json")]
output_files = [os.path.join(currPath, "train.json"), os.path.join(currPath, "dev.json")]
label_output_file = os.path.join(currPath, "label.json")
nested_json_to_json(input_files, output_files, label_output_file)

    
 

Generar formato json:

{
    
    
    "sentence": "生生不息CSOL生化狂潮让你填弹狂扫",
    "entities": [
        {
    
    
            "name": "CSOL",
            "type": "游戏",
            "pos": [
                4,
                7
            ]
        }
    ]
},

Resumir

Es un artículo de conversión de formato de conjunto de datos relativamente completo en el campo NER. Casi todos los conjuntos de datos pueden usar la rueda de código anterior para la conversión de formato. Puede haber algunas etiquetas especiales. Por ejemplo, el formato "B-" en BIO puede ser " B_", o El token y la etiqueta no están separados por espacios. Solo necesita modificar el código para resolverlo. Espero que este blog pueda ser útil para los lectores. Si hay un formato de datos complementario, comuníquese con el blogger ~

Supongo que te gusta

Origin blog.csdn.net/HERODING23/article/details/131610215
Recomendado
Clasificación