Skip to content

VB.NET and Python equivalence

by Steve Cooper on November 10th, 2010

A recent post on Hacker News made me wonder if <inflammatory>Python is just VB.NET without ‘End If’. </inflammatory>

I thought I’d try to translate Peter Norvig’s masterful spellchecker program in Python into VB.NET 2008. Could his beautiful little program be converted line-by-line into VB? The answer is yes.

Here’s the original program;

import re, 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('big.txt').read()))

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits1(word):
   splits     = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes    = [a + b[1:] for a, b in splits if b]
   transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
   replaces   = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   inserts    = [a + c + b     for a, b in splits for c in alphabet]
   return set(deletes + transposes + replaces + inserts)

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):
    candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
    return max(candidates, key=NWORDS.get)

And here’s the equivalent VB;

Option Strict Off
Imports System.Text.RegularExpressions
Imports System.Collections.Generic

Module NorvigSpellChecker

    Dim NWORDS

    Dim alphabet As String = "abcdefghijklmnopqrstuvwxyz"

    Function words(ByVal text)
        Return From match In Regex.Matches(text.ToLower(), "[a-z]+") Select match.Value
    End Function

    Function train(ByVal features)
        Dim model = New DefaultDict(Function() 1)
        For Each f In features
            model(f) += 1
        Next
        Return model
    End Function

    Function edits1(ByVal word) As IEnumerable(Of Object)
        Dim splits = From i In Enumerable.Range(0, len(word)) Let a = word.Substring(0, i), b = word.Substring(i) Select a, b
        Dim deletes = From split In splits Where ifs(split.b) Select split.a + split.b.Substring(1)
        Dim transposes = From split In splits Where len(split.b) > 1 Select split.a + split.b.Substring(1, 1) + split.b.Substring(0, 1) + split.b.Substring(2)
        Dim replaces = From split In splits From c In alphabet Where ifs(split.b) Select split.a + c + split.b.Substring(1)
        Dim inserts = From split In splits From c In alphabet Select split.a + c + split.b
        Return deletes.Union(transposes).Union(replaces).Union(inserts).Distinct()
    End Function

    Function known_edits2(ByVal word)
        Return edits1(word).SelectMany(Function(e1) edits1(e1)).Distinct().Where(Function(e) NWORDS.ContainsKey(e))
    End Function

    Function known(ByVal words As IEnumerable)
        Return From w In words Where NWORDS.ContainsKey(w) Select w
    End Function

    Function correct(ByVal word)
        Dim candidates = ORR(Function() known(New String() {word}), Function() known(edits1(word)), Function() known_edits2(word), Function() New String() {word})
        Return candidates.OrderBy(Function(candidate) NWORDS(candidate)).FirstOrDefault()
    End Function

End Module

Because I needed to define some python-equivalents, like the len(string) function, I ended up writing a bit more code, just to try to get a more exact match. Also, LINQ expressions need to know that certain things are enumerable, so I needed to litter a few type declarations through the code; about half a dozen. But overall I’m happy with the result. Take off the block terminators — ‘End Function’, ‘Next’, and ‘End Module’ — and you end up with a line-perfect equivalent.

Full source code on github

From → Uncategorized

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS