I'm trying to teach myself the Python language with the Google Python class (http://code.google.com/edu/languages/google-python-class/set-up.html).
With the exercise 'wordcount' I get a Traceback error (with the main function and sys.exit(1) function). Even with the solution script (as displayed here).

Does anyone recognize this problem and can some one tell me what I'm missing here?

wordcount gives the following output:
usage: ./wordcount.py {--count | --topcount} file

Traceback (most recent call last):
File "F:\Science\google-python-exercises\basic\solution\wordcount.py", line 114, in <module>
File "F:\Science\google-python-exercises\basic\solution\wordcount.py", line 101, in main
SystemExit: 1

The code:

import sys

def word_count_dict(filename):
  """Returns a word/count dict for this filename."""
# Utility used by count() and Topcount().
  filename = 'f:\Science\google-python-exercises\basic\solution\small.txt'
  word_count = {}  
  input_file = open(filename, 'r')
  for line in input_file:
    words = line.split()
    for word in words:
      word = word.lower()
      # Special case if we're seeing this word for the first time.
      if not word in word_count:
        word_count[word] = 1
        word_count[word] = word_count[word] + 1
  input_file.close()  # Not strictly required, but good form.
  return word_count

def print_words(filename):
  """Prints one per line '<word> <count>' sorted by word for the given file."""
  word_count = word_count_dict(filename)
  words = sorted(word_count.keys())
  for word in words:
    print word, word_count[word]

def get_count(word_count_tuple):
  """Returns the count from a dict word/count tuple  -- used for custom sort."""
  return word_count_tuple[1]

def print_top(filename):
  """Prints the top count listing for the given file."""
  word_count = word_count_dict(filename)

  # Each item is a (word, count) tuple.
  # Sort them so the big counts are first using key=get_count() to extract count.
  items = sorted(word_count.items(), key=get_count, reverse=True)

  # Print the first 20
  for item in items[:20]:
    print item[0], item[1]

def main():
  if len(sys.argv) != 3:
    print 'usage: ./wordcount.py {--count | --topcount} file'

  option = sys.argv[1]
  filename = sys.argv[2]
  if option == '--count':
  elif option == '--topcount':
    print 'unknown option: ' + option

if __name__ == '__main__':

Edited 4 Years Ago by sinnebril: Put in the small.txt file

We are not what we should be
We are not what we need to be
But at least we are not what we used to be
  -- Football Coach

You did not give correct arguments as explained by usage message.

I don't understand what you mean, could you please explain yourself?


Still I don't get what should I type in command prompt.
Could you please help me?



Still I don't get what should I type in command prompt.
Could you please help me?


This question has already been answered. Start a new discussion instead.