Python拼写检查如何更简单的使用

Python 拼写检查在使用的时候有些问题一直在困扰着我们。其实只有不断的学习才能更好的使用这门语言。这几天在翻旧代码时发现以前写的注释部分有很多单词拼写错误,这些单词错得不算离谱,应该可以用工具自动纠错绝大部分。

专注于为中小企业提供成都网站制作、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业密云免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

用 Python 拼写检查脚本很容易,如果能很好利用 aspell/ispell 这些现成的小工具就更简单了。

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

 
 
 
  1. #!/usr/bin/python
  2. # A simple spell checker
  3. # written by http://www.vpsee.com 
  4. import os, sys, subprocess, signal
  5. alphabet = 'abcdefghijklmnopqrstuvwxyz'
  6. def found(word, args, cwd = None, shell = True):
  7. child = subprocess.Popen(args,
  8. shellshell = shell,
  9. stdin = subprocess.PIPE,
  10. stdout = subprocess.PIPE,
  11. cwdcwd = cwd,
  12. universal_newlines = True)
  13. child.stdout.readline()
  14. (stdout, stderr) = child.communicate(word)
  15. if ": " in stdout:
  16. # remove \n\n
  17. stdoutstdout = stdout.rstrip("\n")
  18. # remove left part until :
  19. left, candidates = stdout.split(": ", 1)
  20. candidatescandidates = candidates.split(", ")
  21. # making an error on the first letter of a word is less
  22. # probable, so we remove those candidates and append them
  23. # to the tail of queue, make them less priority
  24. for item in candidates:
  25. if item[0] != word[0]:
  26. candidates.remove(item)
  27. candidates.append(item)
  28. return candidates
  29. else:
  30. return None
  31. # copy from http://norvig.com/spell-correct.html
  32. def edits1(word):
  33. n = len(word)
  34. return set([word[0:i]+word[i+1:] for i in range(n)] +
  35. [word[0:i]+word[i+1]+word[i]+word[i+2:] for i in range(n-1)] +
  36. [word[0:i]+c+word[i+1:] for i in range(n) for c in alphabet] +
  37. [word[0:i]+c+word[i:] for i in range(n+1) for c in alphabet])
  38. def correct(word):
  39. candidates1 = found(word, 'aspell -a')
  40. if not candidates1:
  41. print "no suggestion"
  42. return 
  43. candidates2 = edits1(word)
  44. candidates = []
  45. for word in candidates1:
  46. if word in candidates2:
  47. candidates.append(word)
  48. if not candidates:
  49. print "suggestion: %s" % candidates1[0]
  50. else:
  51. print "suggestion: %s" % max(candidates)
  52. def signal_handler(signal, frame):
  53. sys.exit(0)
  54. if __name__ == '__main__':
  55. signal.signal(signal.SIGINT, signal_handler)
  56. while True:
  57. input = raw_input()
  58. correct(input)

以上就是对Python 拼写检查的相关解决方案。

文章名称:Python拼写检查如何更简单的使用
网站路径:http://www.gawzjz.com/qtweb/news19/176019.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联