单词纠错

在我们平时使用Word或者其他文字编辑软件的时候,常常会遇到单词纠错的功能。比如在Word中:

单词拼写错误

单词纠错算法

首先,我们需要一个语料库,基本上所有的NLP任务都会有语料库。单词纠错的语料库为bit.txt,里面包含的内容如下:

Gutenberg语料库数据;

维基词典;

英国国家语料库中的最常用单词列表。

下载的网址为:https://github.com/percent4/-word- 。

Python实现

实现单词纠错的完整Python代码(spelling_correcter.py)如下:

# -*- coding: utf-8 -*-

import re, collections

def tokens(text):

"""

Get all words from the corpus

"""

return re.findall('[a-z]+', text.lower())

with open('E://big.txt', 'r') as f:

WORDS = tokens(f.read())

WORD_COUNTS = collections.Counter(WORDS)

def known(words):

"""

Return the subset of words that are actually

in our WORD_COUNTS dictionary.

"""

return {w for w in words if w in WORD_COUNTS}

def edits0(word):

"""

Return all strings that are zero edits away

from the input word (i.e., the word itself).

"""

return {word}

def edits1(word):

"""

Return all strings that are one edit away

from the input word.

"""

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def splits(word):

"""

Return a list of all possible (first, rest) pairs

that the input word is made of.

"""

return [(word[:i], word[i:]) for i in range(len(word) + 1)]

pairs = splits(word)

deletes = [a + b[1:] for (a, b) in pairs if b]

transposes = [a + b[1] + b[0] + b[2:] for (a, b) in pairs if len(b) > 1]

replaces = [a + c + b[1:] for (a, b) in pairs for c in alphabet if b]

inserts = [a + c + b for (a, b) in pairs for c in alphabet]

return set(deletes + transposes + replaces + inserts)

def edits2(word):

"""

Return all strings that are two edits away

from the input word.

"""

return {e2 for e1 in edits1(word) for e2 in edits1(e1)}

def correct(word):

"""

Get the best correct spelling for the input word

"""

# Priority is for edit distance 0, then 1, then 2

# else defaults to the input word itself.

candidates = (known(edits0(word)) or

known(edits1(word)) or

known(edits2(word)) or

[word])

return max(candidates, key=WORD_COUNTS.get)

def correct_match(match):

"""

Spell-correct word in match,

and preserve proper upper/lower/title case.

"""

word = match.group()

def case_of(text):

"""

Return the case-function appropriate

for text: upper, lower, title, or just str.:

"""

return (str.upper if text.isupper() else

str.lower if text.islower() else

str.title if text.istitle() else

str)

return case_of(word)(correct(word.lower()))

def correct_text_generic(text):

"""

Correct all the words within a text,

returning the corrected text.

"""

return re.sub('[a-zA-Z]+', correct_match, text)

测试

有了上述的单词纠错程序,接下来我们对一些单词或句子做测试。如下:

original_word_list = ['fianlly', 'castel', 'case', 'monutaiyn', 'foresta', \

'helloa', 'forteen', 'persreve', 'kisss', 'forteen helloa', \

'phons forteen Doora. This is from Chinab.']

for original_word in original_word_list:

correct_word = correct_text_generic(original_word)

print('Orginial word: %s\nCorrect word: %s'%(original_word, correct_word))

输出结果如下:

Orginial word: fianlly

接着,我们对如下的Word文档(Spelling Error.docx)进行测试(下载地址为:https://github.com/percent4/-word-),

有单词错误的Word文档

对该文档进行单词纠错的Python代码如下:

from docx import Document

from nltk import sent_tokenize, word_tokenize

from spelling_correcter import correct_text_generic

from docx.shared import RGBColor

# 文档中修改的单词个数

COUNT_CORRECT = 0

#获取文档对象

file = Document("E://Spelling Error.docx")

#print("段落数:"+str(len(file.paragraphs)))

punkt_list = r",.?\"'!()/\\-<>:@#$%^&*~"

document = Document() # word文档句柄

def write_correct_paragraph(i):

global COUNT_CORRECT

# 每一段的内容

paragraph = file.paragraphs[i].text.strip()

# 进行句子划分

sentences = sent_tokenize(text=paragraph)

# 词语划分

words_list = [word_tokenize(sentence) for sentence in sentences]

p = document.add_paragraph(' '*7) # 段落句柄

for word_list in words_list:

for word in word_list:

# 每一句话第一个单词的第一个字母大写,并空两格

if word_list.index(word) == 0 and words_list.index(word_list) == 0:

if word not in punkt_list:

p.add_run(' ')

# 修改单词,如果单词正确,则返回原单词

correct_word = correct_text_generic(word)

# 如果该单词有修改,则颜色为红色

if correct_word != word:

colored_word = p.add_run(correct_word[0].upper()+correct_word[1:])

font = colored_word.font

font.color.rgb = RGBColor(0x00, 0x00, 0xFF)

COUNT_CORRECT += 1

else:

p.add_run(correct_word[0].upper() + correct_word[1:])

else:

p.add_run(word)

else:

p.add_run(' ')

# 修改单词,如果单词正确,则返回原单词

correct_word = correct_text_generic(word)

if word not in punkt_list:

# 如果该单词有修改,则颜色为红色

if correct_word != word:

colored_word = p.add_run(correct_word)

font = colored_word.font

font.color.rgb = RGBColor(0xFF, 0x00, 0x00)

COUNT_CORRECT += 1

else:

p.add_run(correct_word)

else:

p.add_run(word)

for i in range(len(file.paragraphs)):

write_correct_paragraph(i)

document.save('E://correct_document.docx')

print('修改并保存文件完毕!')

print('一共修改了%d处。'%COUNT_CORRECT)

输出的结果如下:

修改并保存文件完毕!

修改后的Word文档如下:

单词纠错后的Word文档

其中的红色字体部分为原先的单词有拼写错误,进行拼写纠错后的单词,一共修改了19处。

总结

单词纠错实现起来并没有想象中的那么难,但也不是那么容易~https://github.com/percent4/-word- 。

python 单词纠错_用 Python 实现英文单词纠错功能相关推荐

  1. python 单词纠错_自然语言处理1——语言处理与Python(内含纠错)

    学习Python自然语言处理,记录一下学习笔记. 运用Python进行自然语言处理需要用到nltk库,关于nltk库的安装,我使用的pip方式. pip nltk 或者下载whl文件进行安装.(推荐p ...

  2. python 单词长度_用python手刃leetcode(58):最后一个单词的长度【简单题】

    前言 博客里新开一个"用python手刃Leetcode"的专题,顾名思义,主要目的是记录自己在Leetcode上刷题的过程,代码全程用python3编写,所用网址是:leetco ...

  3. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  4. python 概率分布模型_使用python的概率模型进行公司估值

    python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...

  5. python集群_使用Python集群文档

    python集群 Natural Language Processing has made huge advancements in the last years. Currently, variou ...

  6. python高斯求和_利用Python进行数据分析(3)- 列表、元组、字典、集合

    本文主要是对Python的数据结构进行了一个总结,常见的数据结构包含:列表list.元组tuple.字典dict和集合set. image 索引 左边0开始,右边-1开始 通过index()函数查看索 ...

  7. python希腊字母字符串_#10 Python字符串

    前言 通过上一节可知,Python6个序列的内置类型中,最常见的是列表和元组,但在Python中,最常用的数据类型却不是列表和元组,而是字符串.要想深入了解字符串,必须先掌握字符编码问题.因此本篇博文 ...

  8. python做流程图_少儿Python编程_第十四讲:开发游戏

    无论哪一种编程语言,实现图形界面程序的方法都大同小异.本讲介绍用Python开发小游戏的方法,从中学习使用Python编写图形界面的程序,图形图像的基础知识,以及在图形界面程序中与用户交互.最后部分还 ...

  9. python 网页编程_通过Python编程检索网页

    python 网页编程 The internet and the World Wide Web (WWW), is probably the most prominent source of info ...

最新文章

  1. 软件文本框横线_免费开源剪辑软件Shotcut推荐和使用教程
  2. (004) java后台开发之Eclipse(Neon) 版本安装Java EE插件
  3. WINCE系统启动时是否clean boot
  4. linux bash 局部变量赋值,linux之bash的基础特性(四)变量,配置文件及env,printenv,export,declare,set,unset,readonly简单命令...
  5. [转载]Informix Dynamic Server维护手册
  6. 无服务器安全性:将其置于自动驾驶仪上
  7. LeetCode 1042. 不邻接植花(图的数据结构)
  8. 排列组合算法之三: 递归法
  9. linux内存管理---虚拟地址、逻辑地址、线性地址、物理地址的区别(一)
  10. 反射方式,获取出集合ArrayList类的class文件对象
  11. 机器学习及其MATLAB实现——BP神经网络
  12. 安装Visual Studio2019一直显示网络未连接
  13. 1919获阿里20亿投资,独角兽如何搅动酒饮业格局
  14. Linux下的桥接模式
  15. CentOS安装后不能连网的问题
  16. 批量备份交换机路由器配置
  17. linux 基础命令测试题,grep命令基础练习题
  18. 语言学大师 —— 乔姆斯基
  19. 血赚,一顿小烧烤就从阿里P8手上拿到这份内部SpringCloud手册
  20. 入职华为小半年小记一下

热门文章

  1. babel-预设和插件
  2. 堆和栈得区别--向WXP学习
  3. 智慧出击,浪潮云海为海上风电打个样
  4. python中空格怎么打_Python中如何打印空行
  5. 数模备战——基础知识笔记
  6. 游戏数据后台,kafka代替rsync同步日志数据
  7. 深信服AD应用交付介绍
  8. 解读Gartner2013应用交付市场魔力象限
  9. matlab 可见度和衬噪比
  10. PS从入门到精通第3节