Count Words In A File With Exceptions In Python
Join the DZone community and get the full member experience.Join For Free
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 # Get the words to not count skipwords = args.split(' ') # Loop through the file and read each line into our lines list for line in open(filename): lines.append(line) # 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 words.append(word) # 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)
Opinions expressed by DZone contributors are their own.