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 相关文章推荐
python mysqldb连接数据库
Mar 16 Python
python 将md5转为16字节的方法
May 29 Python
Python中is和==的区别详解
Nov 15 Python
用Pycharm实现鼠标滚轮控制字体大小的方法
Jan 15 Python
python+selenium实现自动化百度搜索关键词
Jun 03 Python
python语言基本语句用法总结
Jun 11 Python
Python3监控windows,linux系统的CPU、硬盘、内存使用率和各个端口的开启情况详细代码实例
Mar 18 Python
django 利用Q对象与F对象进行查询的实现
May 15 Python
python中有帮助函数吗
Jun 19 Python
Python实现手绘图效果实例分享
Jul 22 Python
Python 开发工具通过 agent 代理使用的方法
Sep 27 Python
Django实现在线无水印抖音视频下载(附源码及地址)
May 06 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
PHP 循环删除无限分类子节点的实现代码
2013/06/21 PHP
163的邮件用phpmailer发送(实例详解)
2013/06/24 PHP
PHP使用Face++接口开发微信公众平台人脸识别系统的方法
2015/04/17 PHP
Zend Framework基本页面布局分析
2016/03/19 PHP
PDO::beginTransaction讲解
2019/01/27 PHP
教你如何解密js/vbs/vbscript加密的编码异处理小结
2008/06/25 Javascript
网页禁用右键实现代码(JavaScript代码)
2009/10/29 Javascript
javascript写的日历类(基于pj)
2010/12/28 Javascript
jQuery 拖动层(在可视区域范围内)
2012/05/24 Javascript
jQuery实现垂直半透明手风琴特效代码分享
2015/08/21 Javascript
Javascript编程之继承实例汇总
2015/11/28 Javascript
JS仿百度自动下拉框模糊匹配提示
2016/07/25 Javascript
jQuery多选框选择数量限制方法
2017/02/08 Javascript
jQuery Autocomplete简介_动力节点Java学院整理
2017/07/17 jQuery
vue中axios解决跨域问题和拦截器的使用方法
2018/03/07 Javascript
django使用channels2.x实现实时通讯
2018/11/28 Javascript
jQuery实现提交表单时不提交隐藏div中input的方法
2019/10/08 jQuery
JS数据类型分类及常用判断方法
2020/11/19 Javascript
python django集成cas验证系统
2014/07/14 Python
Python基础学习之常见的内建函数整理
2017/09/06 Python
Python实现的根据文件名查找数据文件功能示例
2018/05/02 Python
Python3简单实现串口通信的方法
2019/06/12 Python
python中比较两个列表的实例方法
2019/07/04 Python
django解决订单并发问题【推荐】
2019/07/31 Python
Python利用 utf-8-sig 编码格式解决写入 csv 文件乱码问题
2020/02/21 Python
css3实现六边形边框的实例代码
2019/05/24 HTML / CSS
HTML5 canvas基本绘图之绘制线段
2016/06/27 HTML / CSS
美国求婚钻戒网站:Super Jeweler
2016/08/27 全球购物
马来西亚演唱会订票网站:StubHub马来西亚
2018/10/18 全球购物
大学生的自我鉴定范文
2014/01/21 职场文书
村长贪污检举信
2014/04/04 职场文书
4s店市场专员岗位职责
2014/04/09 职场文书
ktv筹备计划书
2014/05/03 职场文书
党员四风自我剖析材料
2014/10/07 职场文书
教师节主持词开场白
2015/05/29 职场文书
python使用pymysql模块操作MySQL
2021/06/16 Python