Wednesday, May 20, 2009

JavaOne Talk: Python Word Sort

See this post about why this code is being shown. See this post for the Java version to compare against.

class PyWordSort(object):
def __init__(self, fileName):
print "init " + fileName
self.dataFile = open(fileName)
self.words = []
def sortedWords(self):
if len(self.words) == 0:
for line in self.dataFile:
for word in line.split():
self.words.sort(lambda w,w1: cmp(w.lower(), w1.lower()))
return self.words

1 comment:

David Pollak said...

Can't resist... the Scala version:

case class WordSort(filename: String) {

lazy val sortedWords =
(for {
line <- Source.fromFile(filename).getLines.toList
word <- line.trim.split(" ")
} yield word.trim).sort(_ < _)