当前位置:   article > 正文

拼写检查器——朴素贝叶斯应用_′if′ijf′iaf,

′if′ijf′iaf,

How to Write a Spelling Corrector

作者利用飞行的时间写了一个小代码,实现单词拼写检查功能,基本原理仍是朴素贝叶斯原理。

代码仅仅20多行,精湛强大,值得学习。至于朴素贝叶斯算法,作者作了简单的介绍。

(下面代码是注释了的,很详细,借鉴凉茶方便面

  1. import re, collections
  2. #返回单词的列表
  3. #通过正则表达式取出纯字母组成的单词列表
  4. def words(text): return re.findall('[a-z]+', text.lower())
  5. #训练,获得模型
  6. #其实也就是统计每个单词出现的次数,用于计算每个单词出现的频率
  7. #事实上并不是真的在计算单词的出现次数,因为默认词频(没有在big.txt中的单词频率)为1,
  8. #所以统计出的词频会比统计次数多1(称为“平滑”)
  9. def train(features):
  10. model = collections.defaultdict(lambda: 1)
  11. for f in features:
  12. model[f] += 1
  13. return model
  14. #读取整个文本,并且把文本中的单词进行统计
  15. NWORDS = train(words(file('big.txt').read()))
  16. #小写字母列表
  17. alphabet = 'abcdefghijklmnopqrstuvwxyz'
  18. #计算每个与给定单词编辑距离为1的单词,并组成一个集合
  19. def edits1(word):
  20. #将每个单词都分割为两两一组,方便后边的编辑距离的计算
  21. #(如‘if’,分割为[('','if'),('i','f'),('if','')])
  22. splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
  23. #删除的编辑距离:每次从b字符串中删除一个字符
  24. #如‘if’,形成的列表为['f', 'i'],只对前两组进行了分割,因为第三组的b是空串''
  25. deletes = [a + b[1:] for a, b in splits if b]
  26. #交换的编辑距离:单词中相邻的字母位置被交换
  27. #如‘if’,形成的列表为['fi'],只对第一组进行了字母交换,因为只有b的长度大于2才能交换
  28. transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
  29. #替换的编辑距离:每次替换b中的一个字母
  30. # 如‘if’,形成的列表为
  31. #['af', 'bf', 'cf', 'df', 'ef', 'ff', 'gf', 'hf', 'if', 'jf', 'kf', 'lf', 'mf',
  32. # 'nf', 'of', 'pf', 'qf', 'rf', 'sf', 'tf', 'uf', 'vf', 'wf', 'xf', 'yf', 'zf',
  33. # 'ia', 'ib', 'ic', 'id', 'ie', 'if', 'ig', 'ih', 'ii', 'ij', 'ik', 'il', 'im',
  34. # 'in', 'io', 'ip', 'iq', 'ir', 'is', 'it', 'iu', 'iv', 'iw', 'ix', 'iy', 'iz']
  35. replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
  36. #插入的编辑距离:向每个单词分割的组插入一个字母
  37. # 如‘if’,形成的列表为:
  38. #['aif', 'bif', 'cif', 'dif', 'eif', 'fif', 'gif', 'hif', 'iif', 'jif', 'kif',
  39. # 'lif', 'mif', 'nif', 'oif', 'pif', 'qif', 'rif', 'sif', 'tif', 'uif', 'vif',
  40. # 'wif', 'xif', 'yif', 'zif', 'iaf', 'ibf', 'icf', 'idf', 'ief', 'iff', 'igf',
  41. # 'ihf', 'iif', 'ijf', 'ikf', 'ilf', 'imf', 'inf', 'iof', 'ipf', 'iqf', 'irf',
  42. # 'isf', 'itf', 'iuf', 'ivf', 'iwf', 'ixf', 'iyf', 'izf', 'ifa', 'ifb', 'ifc',
  43. # 'ifd', 'ife', 'iff', 'ifg', 'ifh', 'ifi', 'ifj', 'ifk', 'ifl', 'ifm', 'ifn',
  44. # 'ifo', 'ifp', 'ifq', 'ifr', 'ifs', 'ift', 'ifu', 'ifv', 'ifw', 'ifx', 'ify', 'ifz']
  45. inserts = [a + c + b for a, b in splits for c in alphabet]
  46. return set(deletes + transposes + replaces + inserts)
  47. #计算出编辑距离为2的单词集合
  48. #e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS
  49. # 1.计算与给定单词编辑距离为1的单词列表
  50. # 2.计算与编辑距离为1的单词列表的编辑距离为1的列表(也就是编辑距离为2的单词列表)
  51. # 3.如果单词编辑距离为2的单词在文本中,就认为是可用的单词
  52. def known_edits2(word):
  53. return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
  54. #计算单词列表words中,在文件中的单词的列表(也就是只保留可能是单词的,其他的没有出现在文本中的都判断为非单词)
  55. #对于非单词的将不认为是候选单词
  56. def known(words): return set(w for w in words if w in NWORDS)
  57. #计算候选单词中词频最大的单词
  58. def correct(word):
  59. #这里牵扯到python中or的用法,在这里,当known([word])不为False则返回它,否则继续计算known(edits1(word))
  60. #如果known(edits1(word))不为False则返回known(edits1(word)),否则继续。
  61. #这里这么做的原因:
  62. #1. 如果单词是在已知列表中,那就是正确的直接返回它即可
  63. #2. 如果单词是未知的,那么看看与它编辑距离为1的单词,如果有,那么就计算它们的最大概率那么
  64. #3. 编辑距离为1的没有,那就找编辑距离为2的
  65. #4. 如果单词未知,且编辑距离为1,2的也找不到,那么只能返回它本身了
  66. #or的用法:x or y 表示 if x is false, then y, else x,
  67. # it only evaluates the second argument if the first one is False
  68. # 所以当x为True时,也就不再计算y直接返回x
  69. candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
  70. #通过统计candidates中的单词在NWORDS字典中最大的那个单词,并返回它
  71. return max(candidates, key=NWORDS.get)

下面这个是官方网站上原始代码(注释部分有些尴尬):

  1. import re
  2. from collections import Counter
  3. def words(text): return re.findall(r'\w+', text.lower())
  4. WORDS = Counter(words(open('big.txt').read()))
  5. def P(word, N=sum(WORDS.values())):
  6. "Probability of `word`."
  7. return WORDS[word] / N
  8. def correction(word):
  9. "Most probable spelling correction for word."
  10. return max(candidates(word), key=P)
  11. def candidates(word):
  12. "Generate possible spelling corrections for word."
  13. return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
  14. def known(words):
  15. "The subset of `words` that appear in the dictionary of WORDS."
  16. return set(w for w in words if w in WORDS)
  17. def edits1(word):
  18. "All edits that are one edit away from `word`."
  19. letters = 'abcdefghijklmnopqrstuvwxyz'
  20. splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
  21. deletes = [L + R[1:] for L, R in splits if R]
  22. transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
  23. replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
  24. inserts = [L + c + R for L, R in splits for c in letters]
  25. return set(deletes + transposes + replaces + inserts)
  26. def edits2(word):
  27. "All edits that are two edits away from `word`."
  28. return (e2 for e1 in edits1(word) for e2 in edits1(e1))

How It Works: Some Probability Theory

The call correction(w) tries to choose the most likely spelling correction for w. There is no way to know for sure (for example, should "lates" be corrected to "late" or "latest" or "lattes" or ...?), which suggests we use probabilities. We are trying to find the correction c, out of all possible candidate corrections, that maximizes the probability that c is the intended correction, given the original word w:

argmax c ∈ candidates P( c| w)

By Bayes' Theorem this is equivalent to:

argmax c ∈ candidates P( c) P( w| c) / P( w)

Since P(w) is the same for every possible candidate c, we can factor it out, giving:

argmax c ∈ candidates P( c) P( w| c)

The four parts of this expression are:

  1. Selection Mechanism: argmax 
    We choose the candidate with the highest combined probability.

     

  2. Candidate Modelc ∈ candidates
    This tells us which candidate corrections, c, to consider.

     

  3. Language Model: P(c
    The probability that c appears as a word of English text. For example, occurrences of "the" make up about 7% of English text, so we should have P(the) = 0.07.

     

  4. Error Model: P(w|c)
    The probability that w would be typed in a text when the author meant c. For example, P(teh|the) is relatively high, but P(theeexyz|the) would be very low.

One obvious question is: why take a simple expression like P(c|w) and replace it with a more complex expression involving two models rather than one? The answer is that P(c|w) is already conflating two factors, and it is easier to separate the two out and deal with them explicitly. Consider the misspelled wordw="thew" and the two candidate corrections c="the" and c="thaw". Which has a higher P(c|w)? Well, "thaw" seems good because the only change is "a" to "e", which is a small change. On the other hand, "the" seems good because "the" is a very common word, and while adding a "w" seems like a larger, less probable change, perhaps the typist's finger slipped off the "e". The point is that to estimate P(c|w) we have to consider both the probability of c and the probability of the change from c to w anyway, so it is cleaner to formally separate the two factors.

 


测试方法:

  1. tests1 = { 'access': 'acess', 'accessing': 'accesing', 'accommodation':
  2. 'accomodation acommodation acomodation', 'account': 'acount', 'address':
  3. 'adress adres', 'addressable': 'addresable', 'arranged': 'aranged arrainged',
  4. 'arrangeing': 'aranging', 'arrangement': 'arragment', 'articles': 'articals',
  5. 'aunt': 'annt anut arnt', 'auxiliary': 'auxillary', 'available': 'avaible',
  6. 'awful': 'awfall afful', 'basically': 'basicaly', 'beginning': 'begining',
  7. 'benefit': 'benifit', 'benefits': 'benifits', 'between': 'beetween', 'bicycle':
  8. 'bicycal bycicle bycycle', 'biscuits':
  9. 'biscits biscutes biscuts bisquits buiscits buiscuts', 'built': 'biult',
  10. 'cake': 'cak', 'career': 'carrer',
  11. 'cemetery': 'cemetary semetary', 'centrally': 'centraly', 'certain': 'cirtain',
  12. 'challenges': 'chalenges chalenges', 'chapter': 'chaper chaphter chaptur',
  13. 'choice': 'choise', 'choosing': 'chosing', 'clerical': 'clearical',
  14. 'committee': 'comittee', 'compare': 'compair', 'completely': 'completly',
  15. 'consider': 'concider', 'considerable': 'conciderable', 'contented':
  16. 'contenpted contende contended contentid', 'curtains':
  17. 'cartains certans courtens cuaritains curtans curtians curtions', 'decide': 'descide', 'decided':
  18. 'descided', 'definitely': 'definately difinately', 'definition': 'defenition',
  19. 'definitions': 'defenitions', 'description': 'discription', 'desiccate':
  20. 'desicate dessicate dessiccate', 'diagrammatically': 'diagrammaticaally',
  21. 'different': 'diffrent', 'driven': 'dirven', 'ecstasy': 'exstacy ecstacy',
  22. 'embarrass': 'embaras embarass', 'establishing': 'astablishing establising',
  23. 'experience': 'experance experiance', 'experiences': 'experances', 'extended':
  24. 'extented', 'extremely': 'extreamly', 'fails': 'failes', 'families': 'familes',
  25. 'february': 'febuary', 'further': 'futher', 'gallery': 'galery gallary gallerry gallrey',
  26. 'hierarchal': 'hierachial', 'hierarchy': 'hierchy', 'inconvenient':
  27. 'inconvienient inconvient inconvinient', 'independent': 'independant independant',
  28. 'initial': 'intial', 'initials': 'inetials inistals initails initals intials',
  29. 'juice': 'guic juce jucie juise juse', 'latest': 'lates latets latiest latist',
  30. 'laugh': 'lagh lauf laught lugh', 'level': 'leval',
  31. 'levels': 'levals', 'liaison': 'liaision liason', 'lieu': 'liew', 'literature':
  32. 'litriture', 'loans': 'lones', 'locally': 'localy', 'magnificent':
  33. 'magnificnet magificent magnifcent magnifecent magnifiscant magnifisent magnificant',
  34. 'management': 'managment', 'meant': 'ment', 'minuscule': 'miniscule',
  35. 'minutes': 'muinets', 'monitoring': 'monitering', 'necessary':
  36. 'neccesary necesary neccesary necassary necassery neccasary', 'occurrence':
  37. 'occurence occurence', 'often': 'ofen offen offten ofton', 'opposite':
  38. 'opisite oppasite oppesite oppisit oppisite opposit oppossite oppossitte', 'parallel':
  39. 'paralel paralell parrallel parralell parrallell', 'particular': 'particulaur',
  40. 'perhaps': 'perhapse', 'personnel': 'personnell', 'planned': 'planed', 'poem':
  41. 'poame', 'poems': 'poims pomes', 'poetry': 'poartry poertry poetre poety powetry',
  42. 'position': 'possition', 'possible': 'possable', 'pretend':
  43. 'pertend protend prtend pritend', 'problem': 'problam proble promblem proplen',
  44. 'pronunciation': 'pronounciation', 'purple': 'perple perpul poarple',
  45. 'questionnaire': 'questionaire', 'really': 'realy relley relly', 'receipt':
  46. 'receit receite reciet recipt', 'receive': 'recieve', 'refreshment':
  47. 'reafreshment refreshmant refresment refressmunt', 'remember': 'rember remeber rememmer rermember',
  48. 'remind': 'remine remined', 'scarcely': 'scarcly scarecly scarely scarsely',
  49. 'scissors': 'scisors sissors', 'separate': 'seperate',
  50. 'singular': 'singulaur', 'someone': 'somone', 'sources': 'sorces', 'southern':
  51. 'southen', 'special': 'speaical specail specal speical', 'splendid':
  52. 'spledid splended splened splended', 'standardizing': 'stanerdizing', 'stomach':
  53. 'stomac stomache stomec stumache', 'supersede': 'supercede superceed', 'there': 'ther',
  54. 'totally': 'totaly', 'transferred': 'transfred', 'transportability':
  55. 'transportibility', 'triangular': 'triangulaur', 'understand': 'undersand undistand',
  56. 'unexpected': 'unexpcted unexpeted unexspected', 'unfortunately':
  57. 'unfortunatly', 'unique': 'uneque', 'useful': 'usefull', 'valuable': 'valubale valuble',
  58. 'variable': 'varable', 'variant': 'vairiant', 'various': 'vairious',
  59. 'visited': 'fisited viseted vistid vistied', 'visitors': 'vistors',
  60. 'voluntary': 'volantry', 'voting': 'voteing', 'wanted': 'wantid wonted',
  61. 'whether': 'wether', 'wrote': 'rote wote'}
  62. tests2 = {'forbidden': 'forbiden', 'decisions': 'deciscions descisions',
  63. 'supposedly': 'supposidly', 'embellishing': 'embelishing', 'technique':
  64. 'tecnique', 'permanently': 'perminantly', 'confirmation': 'confermation',
  65. 'appointment': 'appoitment', 'progression': 'progresion', 'accompanying':
  66. 'acompaning', 'applicable': 'aplicable', 'regained': 'regined', 'guidelines':
  67. 'guidlines', 'surrounding': 'serounding', 'titles': 'tittles', 'unavailable':
  68. 'unavailble', 'advantageous': 'advantageos', 'brief': 'brif', 'appeal':
  69. 'apeal', 'consisting': 'consisiting', 'clerk': 'cleark clerck', 'component':
  70. 'componant', 'favourable': 'faverable', 'separation': 'seperation', 'search':
  71. 'serch', 'receive': 'recieve', 'employees': 'emploies', 'prior': 'piror',
  72. 'resulting': 'reulting', 'suggestion': 'sugestion', 'opinion': 'oppinion',
  73. 'cancellation': 'cancelation', 'criticism': 'citisum', 'useful': 'usful',
  74. 'humour': 'humor', 'anomalies': 'anomolies', 'would': 'whould', 'doubt':
  75. 'doupt', 'examination': 'eximination', 'therefore': 'therefoe', 'recommend':
  76. 'recomend', 'separated': 'seperated', 'successful': 'sucssuful succesful',
  77. 'apparent': 'apparant', 'occurred': 'occureed', 'particular': 'paerticulaur',
  78. 'pivoting': 'pivting', 'announcing': 'anouncing', 'challenge': 'chalange',
  79. 'arrangements': 'araingements', 'proportions': 'proprtions', 'organized':
  80. 'oranised', 'accept': 'acept', 'dependence': 'dependance', 'unequalled':
  81. 'unequaled', 'numbers': 'numbuers', 'sense': 'sence', 'conversely':
  82. 'conversly', 'provide': 'provid', 'arrangement': 'arrangment',
  83. 'responsibilities': 'responsiblities', 'fourth': 'forth', 'ordinary':
  84. 'ordenary', 'description': 'desription descvription desacription',
  85. 'inconceivable': 'inconcievable', 'data': 'dsata', 'register': 'rgister',
  86. 'supervision': 'supervison', 'encompassing': 'encompasing', 'negligible':
  87. 'negligable', 'allow': 'alow', 'operations': 'operatins', 'executed':
  88. 'executted', 'interpretation': 'interpritation', 'hierarchy': 'heiarky',
  89. 'indeed': 'indead', 'years': 'yesars', 'through': 'throut', 'committee':
  90. 'committe', 'inquiries': 'equiries', 'before': 'befor', 'continued':
  91. 'contuned', 'permanent': 'perminant', 'choose': 'chose', 'virtually':
  92. 'vertually', 'correspondence': 'correspondance', 'eventually': 'eventully',
  93. 'lonely': 'lonley', 'profession': 'preffeson', 'they': 'thay', 'now': 'noe',
  94. 'desperately': 'despratly', 'university': 'unversity', 'adjournment':
  95. 'adjurnment', 'possibilities': 'possablities', 'stopped': 'stoped', 'mean':
  96. 'meen', 'weighted': 'wagted', 'adequately': 'adequattly', 'shown': 'hown',
  97. 'matrix': 'matriiix', 'profit': 'proffit', 'encourage': 'encorage', 'collate':
  98. 'colate', 'disaggregate': 'disaggreagte disaggreaget', 'receiving':
  99. 'recieving reciving', 'proviso': 'provisoe', 'umbrella': 'umberalla', 'approached':
  100. 'aproached', 'pleasant': 'plesent', 'difficulty': 'dificulty', 'appointments':
  101. 'apointments', 'base': 'basse', 'conditioning': 'conditining', 'earliest':
  102. 'earlyest', 'beginning': 'begining', 'universally': 'universaly',
  103. 'unresolved': 'unresloved', 'length': 'lengh', 'exponentially':
  104. 'exponentualy', 'utilized': 'utalised', 'set': 'et', 'surveys': 'servays',
  105. 'families': 'familys', 'system': 'sysem', 'approximately': 'aproximatly',
  106. 'their': 'ther', 'scheme': 'scheem', 'speaking': 'speeking', 'repetitive':
  107. 'repetative', 'inefficient': 'ineffiect', 'geneva': 'geniva', 'exactly':
  108. 'exsactly', 'immediate': 'imediate', 'appreciation': 'apreciation', 'luckily':
  109. 'luckeley', 'eliminated': 'elimiated', 'believe': 'belive', 'appreciated':
  110. 'apreciated', 'readjusted': 'reajusted', 'were': 'wer where', 'feeling':
  111. 'fealing', 'and': 'anf', 'false': 'faulse', 'seen': 'seeen', 'interrogating':
  112. 'interogationg', 'academically': 'academicly', 'relatively': 'relativly relitivly',
  113. 'traditionally': 'traditionaly', 'studying': 'studing',
  114. 'majority': 'majorty', 'build': 'biuld', 'aggravating': 'agravating',
  115. 'transactions': 'trasactions', 'arguing': 'aurguing', 'sheets': 'sheertes',
  116. 'successive': 'sucsesive sucessive', 'segment': 'segemnt', 'especially':
  117. 'especaily', 'later': 'latter', 'senior': 'sienior', 'dragged': 'draged',
  118. 'atmosphere': 'atmospher', 'drastically': 'drasticaly', 'particularly':
  119. 'particulary', 'visitor': 'vistor', 'session': 'sesion', 'continually':
  120. 'contually', 'availability': 'avaiblity', 'busy': 'buisy', 'parameters':
  121. 'perametres', 'surroundings': 'suroundings seroundings', 'employed':
  122. 'emploied', 'adequate': 'adiquate', 'handle': 'handel', 'means': 'meens',
  123. 'familiar': 'familer', 'between': 'beeteen', 'overall': 'overal', 'timing':
  124. 'timeing', 'committees': 'comittees commitees', 'queries': 'quies',
  125. 'econometric': 'economtric', 'erroneous': 'errounous', 'decides': 'descides',
  126. 'reference': 'refereence refference', 'intelligence': 'inteligence',
  127. 'edition': 'ediion ediition', 'are': 'arte', 'apologies': 'appologies',
  128. 'thermawear': 'thermawere thermawhere', 'techniques': 'tecniques',
  129. 'voluntary': 'volantary', 'subsequent': 'subsequant subsiquent', 'currently':
  130. 'curruntly', 'forecast': 'forcast', 'weapons': 'wepons', 'routine': 'rouint',
  131. 'neither': 'niether', 'approach': 'aproach', 'available': 'availble',
  132. 'recently': 'reciently', 'ability': 'ablity', 'nature': 'natior',
  133. 'commercial': 'comersial', 'agencies': 'agences', 'however': 'howeverr',
  134. 'suggested': 'sugested', 'career': 'carear', 'many': 'mony', 'annual':
  135. 'anual', 'according': 'acording', 'receives': 'recives recieves',
  136. 'interesting': 'intresting', 'expense': 'expence', 'relevant':
  137. 'relavent relevaant', 'table': 'tasble', 'throughout': 'throuout', 'conference':
  138. 'conferance', 'sensible': 'sensable', 'described': 'discribed describd',
  139. 'union': 'unioun', 'interest': 'intrest', 'flexible': 'flexable', 'refered':
  140. 'reffered', 'controlled': 'controled', 'sufficient': 'suficient',
  141. 'dissension': 'desention', 'adaptable': 'adabtable', 'representative':
  142. 'representitive', 'irrelevant': 'irrelavent', 'unnecessarily': 'unessasarily',
  143. 'applied': 'upplied', 'apologised': 'appologised', 'these': 'thees thess',
  144. 'choices': 'choises', 'will': 'wil', 'procedure': 'proceduer', 'shortened':
  145. 'shortend', 'manually': 'manualy', 'disappointing': 'dissapoiting',
  146. 'excessively': 'exessively', 'comments': 'coments', 'containing': 'containg',
  147. 'develop': 'develope', 'credit': 'creadit', 'government': 'goverment',
  148. 'acquaintances': 'aquantences', 'orientated': 'orentated', 'widely': 'widly',
  149. 'advise': 'advice', 'difficult': 'dificult', 'investigated': 'investegated',
  150. 'bonus': 'bonas', 'conceived': 'concieved', 'nationally': 'nationaly',
  151. 'compared': 'comppared compased', 'moving': 'moveing', 'necessity':
  152. 'nessesity', 'opportunity': 'oppertunity oppotunity opperttunity', 'thoughts':
  153. 'thorts', 'equalled': 'equaled', 'variety': 'variatry', 'analysis':
  154. 'analiss analsis analisis', 'patterns': 'pattarns', 'qualities': 'quaties', 'easily':
  155. 'easyly', 'organization': 'oranisation oragnisation', 'the': 'thw hte thi',
  156. 'corporate': 'corparate', 'composed': 'compossed', 'enormously': 'enomosly',
  157. 'financially': 'financialy', 'functionally': 'functionaly', 'discipline':
  158. 'disiplin', 'announcement': 'anouncement', 'progresses': 'progressess',
  159. 'except': 'excxept', 'recommending': 'recomending', 'mathematically':
  160. 'mathematicaly', 'source': 'sorce', 'combine': 'comibine', 'input': 'inut',
  161. 'careers': 'currers carrers', 'resolved': 'resoved', 'demands': 'diemands',
  162. 'unequivocally': 'unequivocaly', 'suffering': 'suufering', 'immediately':
  163. 'imidatly imediatly', 'accepted': 'acepted', 'projects': 'projeccts',
  164. 'necessary': 'necasery nessasary nessisary neccassary', 'journalism':
  165. 'journaism', 'unnecessary': 'unessessay', 'night': 'nite', 'output':
  166. 'oputput', 'security': 'seurity', 'essential': 'esential', 'beneficial':
  167. 'benificial benficial', 'explaining': 'explaning', 'supplementary':
  168. 'suplementary', 'questionnaire': 'questionare', 'employment': 'empolyment',
  169. 'proceeding': 'proceding', 'decision': 'descisions descision', 'per': 'pere',
  170. 'discretion': 'discresion', 'reaching': 'reching', 'analysed': 'analised',
  171. 'expansion': 'expanion', 'although': 'athough', 'subtract': 'subtrcat',
  172. 'analysing': 'aalysing', 'comparison': 'comparrison', 'months': 'monthes',
  173. 'hierarchal': 'hierachial', 'misleading': 'missleading', 'commit': 'comit',
  174. 'auguments': 'aurgument', 'within': 'withing', 'obtaining': 'optaning',
  175. 'accounts': 'acounts', 'primarily': 'pimarily', 'operator': 'opertor',
  176. 'accumulated': 'acumulated', 'extremely': 'extreemly', 'there': 'thear',
  177. 'summarys': 'sumarys', 'analyse': 'analiss', 'understandable':
  178. 'understadable', 'safeguard': 'safegaurd', 'consist': 'consisit',
  179. 'declarations': 'declaratrions', 'minutes': 'muinutes muiuets', 'associated':
  180. 'assosiated', 'accessibility': 'accessability', 'examine': 'examin',
  181. 'surveying': 'servaying', 'politics': 'polatics', 'annoying': 'anoying',
  182. 'again': 'agiin', 'assessing': 'accesing', 'ideally': 'idealy', 'scrutinized':
  183. 'scrutiniesed', 'simular': 'similar', 'personnel': 'personel', 'whereas':
  184. 'wheras', 'when': 'whn', 'geographically': 'goegraphicaly', 'gaining':
  185. 'ganing', 'requested': 'rquested', 'separate': 'seporate', 'students':
  186. 'studens', 'prepared': 'prepaired', 'generated': 'generataed', 'graphically':
  187. 'graphicaly', 'suited': 'suted', 'variable': 'varible vaiable', 'building':
  188. 'biulding', 'required': 'reequired', 'necessitates': 'nessisitates',
  189. 'together': 'togehter', 'profits': 'proffits'}
  190. def spelltest(tests, bias=None, verbose=False):
  191. import time
  192. n, bad, unknown, start = 0, 0, 0, time.clock()
  193. if bias:
  194. for target in tests: NWORDS[target] += bias
  195. for target,wrongs in tests.items():
  196. for wrong in wrongs.split():
  197. n += 1
  198. w = correct(wrong)
  199. if w!=target:
  200. bad += 1
  201. unknown += (target not in NWORDS)
  202. if verbose:
  203. print '%r => %r (%d); expected %r (%d)' % (
  204. wrong, w, NWORDS[w], target, NWORDS[target])
  205. return dict(bad=bad, n=n, bias=bias, pct=int(100. - 100.*bad/n),
  206. unknown=unknown, secs=int(time.clock()-start) )
  207. if __name__ == '__main__':
  208. print spelltest(tests1)

 


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/347812
推荐阅读
相关标签
  

闽ICP备14008679号