python Automatic-Corpus-Generation sgml文件解析为csv

最近需要用到文本纠错的数据集,但是是sgml格式的,类似xml格式的,我这里顺手用beautifulsoup解析了一下,核心代码还是来自https://github.com/wdimmy/Automatic-Corpus-Generation,但是我修改了一下,分享一下代码:

import logging
import os
import codecs
from tqdm import tqdm
from bs4 import BeautifulSoup 
import pandas as pd

def replace_char(string,char,index):
    string = list(string)
    string[index] = char
    return ''.join(string)

def read_langs(file_name):

    logging.info(("Reading lines from {}".format(file_name)))
    total_data=[]

    with codecs.open(file_name, "r", "utf-8") as file:

        data = file.read()
        soup = BeautifulSoup(data, 'html.parser')
        results = soup.find_all('sentence')
        for item in tqdm(results):

            text = item.find("text").text.strip()
            correct_text=text
            mistakes = item.find_all("mistake")

            locations = []
            for mistake in mistakes:
                location = mistake.find("location").text.strip()
                wrong =  mistake.find("wrong").text.strip()
                correction_word=mistake.find('correction').text.strip()
                correct_text=replace_char(correct_text,correction_word,int(location)-1)
                locations.append(int(location))
                if text[int(location)-1] != wrong:
                    print("The character of the given location does not equal to the real character")

            sen = list(text)
            tags = ["0" for _ in range(len(sen))]

            for i in locations:
                tags[i - 1] = "1"
            total_data.append([correct_text,text, " ".join(tags)])

    return total_data

file_name='train.sgml'
total_data=read_langs(file_name)




column_name = ['origin_text','random_text','label']
csv_name='Automatic-Corpus-Generation.csv'
xml_df = pd.DataFrame(total_data, columns=column_name)
xml_df.to_csv(csv_name, index=None) 

把它的train.sgml下载下来,就可以开开心心的跑代码了,哈哈哈。

参考文献

[1].A Hybrid Approach to Automatic Corpus Generation for Chinese Spelling Checking (EMNLP2018). https://github.com/wdimmy/Automatic-Corpus-Generation

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值