Over a million developers have joined DZone.

Count Words In A File With Exceptions In Python

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)

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}