Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Counting Words In A Text File

Tags:

python

I'm new to Python and am working on a program that will count the instances of words in a simple text file. The program and the text file will be read from the command line, so I have included into my programming syntax for checking command line arguments. The code is below

import sys

count={}

with open(sys.argv[1],'r') as f:
    for line in f:
        for word in line.split():
            if word not in count:
                count[word] = 1
            else:
                count[word] += 1

print(word,count[word])

file.close()

count is a dictionary to store the words and the number of times they occur. I want to be able to print out each word and the number of times it occurs, starting from most occurrences to least occurrences.

I'd like to know if I'm on the right track, and if I'm using sys properly. Thank you!!

like image 919
Delfino Avatar asked Sep 11 '26 04:09

Delfino


1 Answers

What you did looks fine to me, one could also use collections.Counter (assuming you are python 2.7 or newer) to get a bit more information like the number of each word. My solution would look like this, probably some improvement possible.

import sys
from collections import Counter
lines = open(sys.argv[1], 'r').readlines()
c = Counter()
for line in lines:
    for work in line.strip().split():
        c.update(work)
for ind in c:
    print ind, c[ind]
like image 194
Brian Larsen Avatar answered Sep 13 '26 16:09

Brian Larsen