Back to the main page

Quick script to count occurrences of words

I wanted to know how many times the words in a file appear. So I wrote a Python script that counts them. Please note that the code was written in a hurry and I know it’s possible to make it better.

Here’s it:

import sys

print sys.argv[1]
f = file(sys.argv[1])
buf = ''
while True:
        line = f.readline()
        if len(line) == 0:
        buf += line

buf = buf.replace('n', ' ')
buf = buf.replace('(', ' ')
buf = buf.replace(')', ' ')

arr = buf.split(' ')
dict = {}
for word in arr:
        if not word in dict:
                dict[word] = 0
        dict[word] += 1

for i in sorted(dict.items(), lambda a, b: cmp(b[1], a[1])):
        print '%s: %s' % i

One Response to “Quick script to count occurrences of words”

  1. Max Says:

    Looking for information and found it at this great blog!
    Thanks! blog is powered by WordPress
Entries (RSS) and Comments (RSS).