DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Michael has posted 2 posts at DZone. View Full User Profile

Count Words In A File With Exceptions In Python

  • submit to reddit
        Counts the number of words in a given file, allowing for words not to count

#!/usr/bin/env python

import sys

lines = []
words = []

# Get the command line arguments
args = sys.argv

# Get the name of the file to count the words in
filename = args[1]

# Get the words to not count
skipwords = args[2].split(' ')

# Loop through the file and read each line into our lines list
for line in open(filename):

# Get the number of lines read
numlines = len(lines)

# Loop through the lines list and place the words into the word list
for line in lines:
	# Split each line into individual words
	for word in line.split(' '):
		# Make sure the word is not in our list of words to skip
		if word not in skipwords:
			# If the word is not in our skip list, add it to our word list

# Get the number of words in our list
numwords = len(words)

# Show the number of words and the number of lines
print "%d words in %d lines" % (numwords, numlines)


Snippets Manager replied on Mon, 2009/08/31 - 11:40pm

filename = args[1] skipwords = args[2].split(' ') print reduce( lambda a, b: len(a) + len(b), [filter(lambda t: t not in skipwords,x.split()) for x in open(filename)] )