Python实现单词拼写检查


Posted in Python onApril 25, 2015

这几天在翻旧代码时发现以前写的注释部分有很多单词拼写错误,这些单词错得不算离谱,应该可以用工具自动纠错绝大部分。用 Python 写个拼写检查脚本很容易,如果能很好利用 aspell/ispell 这些现成的小工具就更简单了。

要点

1、输入一个拼写错误的单词,调用 aspell -a 后得到一些候选正确单词,然后用距离编辑进一步?鹧〕龈??返拇省1热缭诵 aspell -a,输入 ‘hella' 后得到如下结果:
hell, Helli, hello, heal, Heall, he'll, hells, Heller, Ella, Hall, Hill, Hull, hall, heel, hill, hula, hull, Helga, Helsa, Bella, Della, Mella, Sella, fella, Halli, Hally, Hilly, Holli, Holly, hallo, hilly, holly, hullo, Hell's, hell's

2、什么是距离编辑(Edit-Distance,也叫 Levenshtein algorithm)呢?就是说给定一个单词,通过多次插入、删除、交换、替换单字符的操作后枚举出所有可能的正确拼写,比如输入 ‘hella',经过多次插入、删除、交换、替换单字符的操作后变成:
‘helkla', ‘hjlla', ‘hylla', ‘hellma', ‘khella', ‘iella', ‘helhla', ‘hellag', ‘hela', ‘vhella', ‘hhella', ‘hell', ‘heglla', ‘hvlla', ‘hellaa', ‘ghella', ‘hellar', ‘heslla', ‘lhella', ‘helpa', ‘hello', …

3、综合上面2个集合的结果,并且考虑到一些理论知识可以提高拼写检查的准确度,比如一般来说写错单词都是无意的或者误打,完全错的单词可能性很小,而且单词的第一个字母一般不会拼错。所以可以在上面集合里去掉第一个字母不符合的单词,比如:'Sella', ‘Mella', khella', ‘iella' 等,这里 VPSee 不删除单词,而把这些单词从队列里取出来放到队列最后(优先级降低),所以实在匹配不了以 h 开头的单词才去匹配那些以其他字母开头的单词。

4、程序中用到了外部工具 aspell,如何在 Python 里捕捉外部程序的输入和输出以便在 Python 程序里处理这些输入和输出呢?Python 2.4 以后引入了 subprocess 模块,可以用 subprocess.Popen 来处理。

5、Google 大牛 Peter Norvig 写了一篇 How to Write a Spelling Corrector 很值得一看,大牛就是大牛,21行 Python 就解决拼写问题,而且还不用外部工具,只需要事先读入一个词典文件。本文程序的 edits1 函数就是从牛人家那里 copy 的。

代码

 

#!/usr/bin/python
# A simple spell checker

import os, sys, subprocess, signal

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def found(word, args, cwd = None, shell = True):
  child = subprocess.Popen(args, 
    shell = shell, 
    stdin = subprocess.PIPE, 
    stdout = subprocess.PIPE, 
    cwd = cwd, 
    universal_newlines = True) 
  child.stdout.readline()
  (stdout, stderr) = child.communicate(word)
  if ": " in stdout:
    # remove \n\n
    stdout = stdout.rstrip("\n")
    # remove left part until :
    left, candidates = stdout.split(": ", 1) 
    candidates = candidates.split(", ")
    # making an error on the first letter of a word is less 
    # probable, so we remove those candidates and append them 
    # to the tail of queue, make them less priority
    for item in candidates:
      if item[0] != word[0]: 
        candidates.remove(item)
        candidates.append(item)
    return candidates
  else:
    return None

# copy from http://norvig.com/spell-correct.html
def edits1(word):
  n = len(word)
  return set([word[0:i]+word[i+1:] for i in range(n)] +           
    [word[0:i]+word[i+1]+word[i]+word[i+2:] for i in range(n-1)] +
    [word[0:i]+c+word[i+1:] for i in range(n) for c in alphabet] +
    [word[0:i]+c+word[i:] for i in range(n+1) for c in alphabet])

def correct(word):
  candidates1 = found(word, 'aspell -a')
  if not candidates1:
    print "no suggestion"
    return 

  candidates2 = edits1(word)
  candidates = []
  for word in candidates1:
    if word in candidates2:
      candidates.append(word)
  if not candidates:
    print "suggestion: %s" % candidates1[0]
  else:
    print "suggestion: %s" % max(candidates)

def signal_handler(signal, frame):
  sys.exit(0)

if __name__ == '__main__':
  signal.signal(signal.SIGINT, signal_handler)
  while True:
    input = raw_input()
    correct(input)

更简单的方法

当然直接在程序里调用相关模块最简单了,有个叫做 PyEnchant 的库支持拼写检查,安装 PyEnchant 和 Enchant 后就可以直接在 Python 程序里 import 了:

>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>
Python 相关文章推荐
基于scrapy实现的简单蜘蛛采集程序
Apr 17 Python
python将字符串转换成数组的方法
Apr 29 Python
tensorflow中next_batch的具体使用
Feb 02 Python
python3.x上post发送json数据
Mar 04 Python
selenium+python实现自动登录脚本
Apr 22 Python
Tensorflow实现AlexNet卷积神经网络及运算时间评测
May 24 Python
Python实现的连接mssql数据库操作示例
Aug 17 Python
Python读写zip压缩文件的方法
Aug 29 Python
Django--权限Permissions的例子
Aug 28 Python
Python常用库大全及简要说明
Jan 17 Python
python实现超级玛丽游戏
Mar 18 Python
django 外键创建注意事项说明
May 20 Python
在Debian下配置Python+Django+Nginx+uWSGI+MySQL的教程
Apr 25 #Python
使用PDB简单调试Python程序简明指南
Apr 25 #Python
Python脚本判断 Linux 是否运行在虚拟机上
Apr 25 #Python
在Python中使用cookielib和urllib2配合PyQuery抓取网页信息
Apr 25 #Python
使用Python的Tornado框架实现一个一对一聊天的程序
Apr 25 #Python
使用Python发送邮件附件以定时备份MySQL的教程
Apr 25 #Python
安装Python的web.py框架并从hello world开始编程
Apr 25 #Python
You might like
UTF8编码内的繁简转换的PHP类
2009/07/09 PHP
ThinkPHP中pathinfo的访问模式、路径访问模式及URL重写总结
2014/08/23 PHP
redis查看连接数及php模拟并发创建redis连接的方法
2016/12/15 PHP
一个用js实现控制台控件的代码
2007/09/04 Javascript
教你如何解密js/vbs/vbscript加密的编码异处理小结
2008/06/25 Javascript
JavaScript入门教程(2) JS基础知识
2009/01/31 Javascript
JavaScript 闭包深入理解(closure)
2009/05/27 Javascript
jQuery动画效果图片轮播特效
2016/01/12 Javascript
JQuery fileupload插件实现文件上传功能
2016/03/18 Javascript
JavaScript和jQuery获取input框的绝对位置实现方法
2016/10/13 Javascript
Jquery给当前页或者跳转后页面的导航栏添加选中后样式的实例
2016/12/08 Javascript
100多个基础常用JS函数和语法集合大全
2017/02/16 Javascript
vue构建单页面应用实战
2017/04/10 Javascript
对mac下nodejs 更新到最新版本的最新方法(推荐)
2018/05/17 NodeJs
[57:55]EG vs Fnatic 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
python写的ARP攻击代码实例
2014/06/04 Python
python通过smpt发送邮件的方法
2015/04/30 Python
Python+Pika+RabbitMQ环境部署及实现工作队列的实例教程
2016/06/29 Python
详解Python中for循环是如何工作的
2017/06/30 Python
Python判断一个三位数是否为水仙花数的示例
2018/11/13 Python
Python3转换html到pdf的不同解决方案
2019/03/11 Python
django实现更改数据库某个字段以及字段段内数据
2020/03/31 Python
怎么解决pycharm license Acti的方法
2020/10/28 Python
python 实现逻辑回归
2020/12/30 Python
Numpy中的数组搜索中np.where方法详细介绍
2021/01/08 Python
英国最大的美妆产品在线零售商之一:Beauty Bay
2017/09/29 全球购物
卡骆驰新加坡官网:Crocs新加坡
2018/06/12 全球购物
SportsDirect.com马来西亚:英国第一体育零售商
2018/11/21 全球购物
生物科学专业职业规划书范文
2014/02/11 职场文书
商场促销活动总结
2014/07/10 职场文书
基层党组织整改方案
2014/10/25 职场文书
师德师风个人整改措施
2014/10/27 职场文书
信仰纪录片观后感
2015/06/08 职场文书
追悼词范文大全
2015/06/23 职场文书
退休欢送会主持词
2015/07/01 职场文书
关于军训的感想
2015/08/07 职场文书