Conversão geral do formato do conjunto de dados NER para o formato JSON Daquan

prefácio

Recentemente, estou realizando tarefas relacionadas à extração geral de modelos grandes. É necessário converter todos os conjuntos de dados no mesmo formato para facilitar a construção de conjuntos de dados de ajuste fino de instruções. Ao processar dados, é necessário converter conjuntos de dados NER em diferentes formatos em dados de formato json fáceis de manusear, o que é uma tarefa muito complicada. No campo do NER, não há especificação de formato unificado. O blogueiro coletou quase 30 conjuntos de dados NER e concluiu que os formatos comuns de conjuntos de dados NER incluem BIO, BIEO, BIO no formato Excel, separação de tags de dados, json incorporado, etc. haver dois ou três conjuntos de dados em cada formato, e codificá-los individualmente exigiria muito esforço e tornaria o trabalho mais lento. Embora existam muitos conjuntos de dados de código aberto que foram processados ​​no formato json no github, isso não abrange todos os conjuntos de dados do NER. É melhor ensinar as pessoas a pescar do que ensiná-las a pescar. Este artigo resumirá o conjunto de dados comum formatos no campo NER. E forneça o código para converter o conjunto de dados em formato json para os leitores pegarem. Além disso, o conjunto de dados processados ​​pode ser baixado aqui . Se for útil para você, curta e incentive o blogueiro ~


1. Visão geral dos conjuntos de dados NER

Existem muitos tipos de conjuntos de dados no domínio NER, e os formatos de conjuntos de dados comuns são mostrados na tabela a seguir:
insira a descrição da imagem aqui

Aqui, primeiro analiso os prós e os contras de diferentes formatos de conjunto de dados e por que escolhi o formato json.

1.1 JSON incorporado

O primeiro é o conjunto de dados Boson-NER representativo com json incorporado e as informações da entidade são marcadas no texto. Embora o tipo de entidade seja muito claro, mas as informações de localização não são marcadas e, para uma amostra, é impossível saber quantos tipos de entidade existem e é difícil obter diretamente.

1.2 BIO

Os tipos de BIO podem ser subdivididos. Um deles é que em um arquivo txt, há apenas um token em uma linha e um token é seguido por seu tipo. O conteúdo geral precisa ser lido verticalmente. O outro formulário é baseado em o texto original por trás de cada token. Juntamente com os tipos de entidade, esses tipos são mais fáceis de ler, mas mais complicados de manusear.

1.3 JSON em camadas

O formato json hierárquico está mais de acordo com o formato final que precisa ser processado uniformemente. Cada amostra é aninhada por um par de chaves, que inclui conteúdo de texto e conteúdo de marca, mas marcas, menções e informações de localização são camadas aninhadas por camada, que é inconveniente para extrair.

1.4 BIEOs

O formato do BIEO é semelhante ao formato do BIO, exceto que há um símbolo especial adicional de fim e os caracteres especiais precisam ser considerados separadamente durante o processamento.

1.5 Separação de rótulos de dados

O formato de dados com separação de rótulos de dados é o pior. Você não pode ver diretamente a entidade nem obter as informações da localização da entidade, mas sua vantagem é que é mais conveniente de manusear. Você só precisa comparar os locais correspondentes dos dois arquivos para extrair a entidade correspondente e as informações de localização.

1.6 json padrão

O padrão aqui é o tipo de formato de dados json para o qual irei eventualmente converter. Pegue a seguinte amostra de dados como exemplo: você
insira a descrição da imagem aqui
pode ver que cada amostra inclui sentença e coleção de entidade, sentença é o conteúdo da amostra e coleção de entidade contém o menção de cada entidade, tipo e informações de localização, esse formato de dados é o formato que eu acho que é melhor processado e também é o formato processado pelo código neste blog.

2. BIO_to_JSON

Tipo de dado 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)

Gerar formato json:

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

3. BIEO_to_JSON

Tipo de dado 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)
    

Gerar formato json:

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

4. BMEO_to_JSON

Tipo de dado 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)

    

Gerar formato json:

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

5.D_BIO_JSON

Tipo de dado 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)

Gerar 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_to_JSON

Tipo de dado 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)

    

Gerar formato json:

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

7. JSON_to_JSON

Tipo de dado 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)
 

Gerar 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_to_JSON

Tipo de dado 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)

    
 

Gerar formato json:

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

Resumir

É um artigo de conversão de formato de conjunto de dados relativamente abrangente no campo NER. Quase todos os conjuntos de dados podem usar a roda de código acima para conversão de formato. Pode haver algumas tags especiais. Por exemplo, o formato "B-" em BIO pode ser " B_", ou O token e o rótulo não são separados por espaços. Você só precisa modificar o código para resolvê-lo. Espero que este blog possa ser útil para os leitores. Se houver um formato de dados suplementar, entre em contato com o blogueiro ~

Acho que você gosta

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