用python识别错别字并矫正

在今日头条编写文章的时候发现一个好用的功能,就是发文助手,当你写文章的时候,发文助手会实时监测文章中的错别字并给出修改建议,非常人性化,那么是怎么实现的呢,今天小编来讲讲怎么实现的 。

用python识别错别字并矫正

一、纠错思路


中文纠错分为两步走,第一步是错误检测,第二步是错误纠正;

错误检测部分先通过结巴中文分词器切词,由于句子中含有错别字,所以切词结果往往会有切分错误的情况,这样从字粒度和词粒度两方面检测错误, 整合这两种粒度的疑似错误结果,形成疑似错误位置候选集;

错误纠正部分,是遍历所有的疑似错误位置,并使用音似、形似词典替换错误位置的词,然后通过语言模型计算句子困惑度,对所有候选集结果比较并排序,得到最优纠正词。

这里推荐一款开源python库pycorrector,github地址:
https://github.com/shibing624/pycorrector
下面来讲解一下具体的安装使用步骤

二、安装

要求python3.6版本
▶全自动安装:
pip install pycorrector
▶半自动安装:
git clone https://github.com/shibing624/pycorrector.git
cd pycorrector
python setup.py install

通过以上两种方法的任何一种完成安装都可以。如果不想安装,可以下载github源码包,安装下面依赖再使用。

▶依赖安装
kenlm安装
pip install https://github.com/kpu/kenlm/archive/master.zip
其他库包安装
pip install -r requirements.txt
▉ 使用方法

▶文本纠错

import pycorrector
corrected_sent, detail = pycorrector.correct('少先队员因该为老人让坐')
print(corrected_sent, detail)
程序运行后输出:

少先队员应该为老人让座 [[('因该', '应该', 4, 6)], [('坐', '座', 10, 11)]]


规则方法默认会从路径~/.pycorrector/datasets/zh_giga.no_cna_cmn.prune01244.klm加载kenlm语言模型文件,如果检测没有该文件,则程序会自动联网下载。当然也可以手动下载模型文件(2.8G)并放置于该位置。下载地址:
https://deepspeech.bj.bcebos.com/zh_lm/zh_giga.no_cna_cmn.prune01244.klm

▶错误检测

import pycorrector
idx_errors = pycorrector.detect('少先队员因该为老人让坐')
print(idx_errors)


程序运行输出:

[['因该', 4, 6, 'word'], ['坐', 10, 11, 'char']]


返回类型是list, [error_word, begin_pos, end_pos, error_type],pos索引位置以0开始。

▶关闭字粒度纠错

import pycorrector
error_sentence_1 = '我的喉咙发炎了要买点阿莫细林吃'
correct_sent = pycorrector.correct(error_sentence_1)
print(correct_sent)

程序输出

'我的喉咙发炎了要买点阿莫西林吉', [['细林', '西林', 12, 14], ['吃', '吉', 14, 15]]

上例中吃发生误纠,如下代码关闭字粒度纠错:

import pycorrector
error_sentence_1 = '我的喉咙发炎了要买点阿莫细林吃'
pycorrector.enable_char_error(enable=False)
correct_sent = pycorrector.correct(error_sentence_1)
print(correct_sent)

程序运行输出:

'我的喉咙发炎了要买点阿莫西林吃', [['细林', '西林', 12, 14]]
默认字粒度、词粒度的纠错都打开,一般情况下单字错误发生较少,而且字粒度纠错准确率较低。关闭字粒度纠错,这样可以提高纠错准确率,提高纠错速度。

默认enable_char_error方法的enable参数为True,即打开错字纠正,这种方式可以召回字粒度错误,但是整体准确率会低;
如果追求准确率而不追求召回率的话,建议将enable设为False,仅使用错词纠正。


▶加载自定义混淆集

通过加载自定义混淆集,支持用户纠正已知的错误,包括两方面功能:1)错误补召回;2)误杀加白。

import pycorrector
pycorrector.set_log_level('INFO')
error_sentences = [
    '买iPhone差,要多少钱',
    '共同实际控制人萧华、霍荣铨、张旗康',
]

for line in error_sentences:
    print(pycorrector.correct(line))
print('*' * 53)
pycorrector.set_custom_confusion_dict(path='./my_custom_confusion.txt')
for line in error_sentences:
    print(pycorrector.correct(line))


程序运行输出:


('买iPhone差,要多少钱', [])   # "iPhone差"漏召,应该是"iphoneX"


('共同实际控制人萧华、霍荣铨、张启康', [['张旗康', '张启康', 14, 17]]) # "张启康"误杀,应该不用纠


*****************************************************


('买iPhoneX,要多少钱', [['iPhone差', 'iPhoneX', 1, 8]])


('共同实际控制人萧华、霍荣铨、张旗康', [])
具体demo见example/use_custom_confusion.py,其中./my_custom_confusion.txt的内容格式如下,以空格间隔:


iPhone差 iPhoneX 100


张旗康 张旗康


set_custom_confusion_dict方法的path参数为用户自定义混淆集文件路径。


▶加载自定义语言模型


默认提供下载并使用的kenlm语言模型zh_giga.no_cna_cmn.prune01244.klm文件是2.8G,内存较小的电脑使用pycorrector程序可能会吃力些。


支持用户加载自己训练的kenlm语言模型,或使用2014版人民日报数据训练的模型,模型小(20M),准确率低些。

from pycorrector import Corrector
pwd_path = os.path.abspath(os.path.dirname(__file__))
lm_path = os.path.join(pwd_path, './people_chars_lm.klm')
model = Corrector(language_model_path=lm_path)
corrected_sent, detail = model.correct('少先队员因该为老人让坐')
print(corrected_sent, detail)


程序运行输出:


少先队员应该为老人让座 [[('因该', '应该', 4, 6)], [('坐', '座', 10, 11)]]
具体demo见example/load_custom_language_model.py,其中./people_chars_lm.klm是自定义语言模型文件。


▶英文拼写纠错

支持英文单词的拼写错误纠正。

import pycorrector
sent_lst = ['what', 'hapenning', 'how', 'to', 'speling', 'it', 'you', 'can', 'gorrect', 'it']
for i in sent_lst:
    print(i, '=>', pycorrector.en_correct(i))


程序运行输出:

what => what
hapenning => happening
how => how
to => to
speling => spelling
it => it
you => you
can => can
gorrect => correct
it => it

▶中文简繁互换

支持中文繁体到简体的转换,和简体到繁体的转换。

import pycorrector
traditional_sentence = '憂郁的臺灣烏龜'
simplified_sentence = pycorrector.traditional2simplified(traditional_sentence)
print(traditional_sentence, '=>', simplified_sentence)
simplified_sentence = '忧郁的台湾乌龟'
traditional_sentence = pycorrector.simplified2traditional(simplified_sentence)
print(simplified_sentence, '=>', traditional_sentence)

程序运行输出:

憂郁的臺灣烏龜 => 忧郁的台湾乌龟
忧郁的台湾乌龟 => 憂郁的臺灣烏龜


▶命令行模式

支持批量文本纠错。

python -m pycorrector -h
usage: __main__.py [-h] -o OUTPUT [-n] [-d] input
@description:
positional arguments:
  input                 the input file path, file encode need utf-8.
optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        the output file path.
  -n, --no_char         disable char detect mode.
  -d, --detail          print detail info


例如:

python -m pycorrector input.txt -o out.txt -n -d
输入文件:input.txt;输出文件:out.txt ;关闭字粒度纠错;打印详细纠错信息;纠错结果以 间隔

▶评估

提供评估脚本pycorrector/utils/eval.py,该脚本有两个功能:
构建评估样本集:自动生成评估集pycorrector/data/eval_corpus.json, 包括字粒度错误100条、词粒度错误100条、语法错误100条,正确句子200条。用户可以修改条数生成其他评估样本分布。

计算纠错准召率:采用保守计算方式,简单把纠错之后与正确句子完成匹配的视为正确,否则为错。

执行该脚本后得到,规则方法纠错效果评估如下:

准确率:320/500=64%

召回率:152/300=50.67%

看来还有比较大的提升空间,误杀和漏召回的都有。

{{collectdata}}

网友评论0