Python实现单词拼写检查

 更新时间:2015年04月25日 11:57:25   投稿:junjie  
这篇文章主要介绍了Python实现单词拼写检查,本文讲解了单词拼写检查的一些知识并给出两种实现方法,需要的朋友可以参考下

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

要点

1、输入一个拼写错误的单词,调用 aspell -a 后得到一些候选正确单词,然后用距离编辑进一步嗮选出更精确的词。比如运行 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实现学生管理系统的代码(JSON模块)

    Python实现学生管理系统的代码(JSON模块)

    这篇文章主要介绍了Python实现学生管理系统的代码(JSON模块),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04
  • pycharm 多行批量缩进和反向缩进快捷键介绍

    pycharm 多行批量缩进和反向缩进快捷键介绍

    这篇文章主要介绍了pycharm 多行批量缩进和反向缩进快捷键介绍,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • python模拟Django框架实例

    python模拟Django框架实例

    这篇文章主要为大家详细介绍了python模拟Django框架实例,了解一个web框架需要的基本功能,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • 本地文件上传到七牛云服务器示例(七牛云存储)

    本地文件上传到七牛云服务器示例(七牛云存储)

    这篇文章主要介绍了使用PYTHON把本地文件上传到七牛云服务的方法,开发环境是Python 2.7,大家参考使用吧
    2014-01-01
  • Python命令启动Web服务器实例详解

    Python命令启动Web服务器实例详解

    这篇文章主要介绍了Python命令启动Web服务器实例详解的相关资料,需要的朋友可以参考下
    2017-02-02
  • 查看django执行的sql语句及消耗时间的两种方法

    查看django执行的sql语句及消耗时间的两种方法

    今天小编就为大家分享一篇查看django执行的sql语句及消耗时间的两种方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • Pandas中datetime数据类型的使用

    Pandas中datetime数据类型的使用

    本文主要介绍了Pandas中datetime数据类型的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-12-12
  • Django之路由层的实现

    Django之路由层的实现

    这篇文章主要介绍了Django之路由层的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Python 读取图片文件为矩阵和保存矩阵为图片的方法

    Python 读取图片文件为矩阵和保存矩阵为图片的方法

    下面小编就为大家分享一篇Python 读取图片文件为矩阵和保存矩阵为图片的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04
  • Python编写可视化界面的详细教程(Python+PyCharm+PyQt)

    Python编写可视化界面的详细教程(Python+PyCharm+PyQt)

    最近开始学习Python,但只限于看理论,编几行代码,觉得没有意思,就想能不能用Python编写可视化的界面,遂查找了相关资料,发现了PyQt,所以本文介绍了Python+PyCharm+PyQt编写可视化界面的详细教程,需要的朋友可以参考下
    2024-07-07

最新评论