| Store | Cart

Suggest more finesse, please. I/O and sequences.

From: Qertoip <q...@o2.pl>
Fri, 25 Mar 2005 19:17:30 +0100
Would you like to suggest me any improvements for the following code?
I want to make my implementation as simple, as Python - native, as fine as
possible.

I've written simple code, which reads input text file and creates words'
ranking by number of appearence.

Code:
---------------------------------------------------------------------------
import sys

def moreCommonWord( x, y ):
	if x[1] != y[1]:
		return cmp( x[1], y[1] ) * -1
	return cmp( x[0], y[0] )

wordsDic = {}
inFile = open( sys.argv[1] )
for word in inFile.read().split():
	if wordsDic.has_key( word ):
		wordsDic[word] = wordsDic[word] + 1
	else:
		wordsDic[word] = 1
inFile.close()

wordsLst = wordsDic.items()
wordsLst.sort( moreCommonWord )

outFile = open( sys.argv[2], 'w')
for pair in wordsLst:
	outFile.write( str( pair[1] ).rjust( 7 ) + " : " + str( pair[0] ) + "\n" )
outFile.close()
---------------------------------------------------------------------------

In particular, I don't like reading whole file just to split it. 
It is easy to read by lines - may I read by words with that ease?

PS I've been learning Python since todays morning, so be understanding :>

-- 
Greets,
Piotrek

Recent Messages in this Thread
Qertoip Mar 25, 2005 06:17 pm
Scott David Daniels Mar 25, 2005 08:51 pm
Qertoip Mar 25, 2005 10:06 pm
Scott David Daniels Mar 25, 2005 11:30 pm
Larry Bates Mar 25, 2005 10:11 pm
Qertoip Mar 26, 2005 01:24 am
Peter Hansen Mar 26, 2005 02:09 am
Qertoip Mar 26, 2005 10:15 am
Peter Hansen Mar 26, 2005 11:46 am
Messages in this thread