• Revista PROGRAMAR: Já está disponível a edição #53 da revista programar. Faz já o download aqui!

Sign in to follow this  
Followers 0

[Python] Corrector ortográfico

1 post in this topic

import re, string, collections

def words(text): return re.findall('[a-z]+', text.lower())

def train(features):
   model = collections.defaultdict(lambda: 1)
   for f in features:
       model[f] += 1
   return model

NWORDS = train(words(file('Documents/holmes.txt').read()))

def edits1(word):
   n = len(word)
   return set([word[0:i]+word[i+1:] for i in range(n)] + ## deletion
              [word[0:i]+word[i+1]+word[i]+word[i+2:] for i in range(n-1)] + ## transposition
              [word[0:i]+c+word[i+1:] for i in range(n) for c in string.lowercase] + ## alteration
              [word[0:i]+c+word[i:] for i in range(n+1) for c in string.lowercase]) ## insertion

def known_edits2(word):
   return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)

def known(words): return set(w for w in words if w in NWORDS)

def correct(word):
   return max(known([word]) or known(edits1(word)) or known_edits2(word) or [word],
              key=lambda w: NWORDS[w])


>>> correct('speling')


>>> correct('korrecter')


Retirado de Norvig.

O site não está disponível neste momento porque está a ser massacrado pelo Digg effect.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0