[Courses] [python] Lesson 4: Modules and command-line arguments

Peggy Russell prusselltechgroup at gmail.com
Mon Jul 11 08:49:03 UTC 2011


========================= Homework ============================
1. num = int(sys.argv[1]):  if you run it and don't give an argument,
   you'll get an error.  Why?
   -----------------------------------------------------------------------------
   `num = int(sys.argv[1])` gives an IndexError when no data is entered.
   There is no index 1. Also a ValueError will be raised if the data is
   not an integer.
   -----------------------------------------------------------------------------

   Can you think of a way to check whether the user forgot to supply an argument,
   and print an error message if so?
   -----------------------------------------------------------------------------
   #!/usr/bin/python3
   #============================================================================
   # Description:
   #   Check that one input argument was entered. If not, print error message.
   #
   # Usage: ./check-argnum i
   # 
   #   Where: i is an integer
   #
   # Revisions (v1.0):
   #   2011.07.11 - 1.0 Created.
   #============================================================================
   import sys
   if (len(sys.argv) == 2):
     num = int(sys.argv[1])
     for i in range(0, num):
       print(i)
   else:
     print("Please supply an integer argument")
   -----------------------------------------------------------------------------

2. Write a program that takes a filename and prints the number of
   lines in the file. (You can check its results with wc -l filename.)
   -----------------------------------------------------------------------------
   #!/usr/bin/python3
   #============================================================================
   # Description:
   #   Count number of lines in a single file.
   #
   # Usage: ./mywordcounter FILE
   #
   #   Where: FILE is a valid file name for your system. An IOError will be
   #          raised if file not found at this time.
   #
   # Revisions (v1.0):
   #   2011.07.11 - 1.0 Handle a single file.
   #============================================================================
   import sys

   fileName = sys.argv[1]
   file = open(fileName)

   lineCnt = 0
   for line in file:
     lineCnt += 1

   file.close()

   print('File "{0}" contains {1} line{2}'.format(fileName,
                                                 lineCnt,
                                                 " " if lineCnt == 1 else "s"))
   -----------------------------------------------------------------------------

3. How would you extend this so that you can count lines in multiple
   files, not just one? So you could say $ mywordcounter file1 file2 file3
   -----------------------------------------------------------------------------
   #!/usr/bin/python3
   #============================================================================
   # Description:
   #   Count number of lines in 1 or more files.
   #
   # Usage: ./mywordcounter FILE...
   #
   #   Where: FILE is a valid file name for your system. An IOError will be
   #          raised if file not found at this time.
   #
   # Revisions (v1.1):
   #   2011.07.11 - 1.1 Handle multiple files.
   #   2011.07.11 - 1.0 Handle a single file.
   #============================================================================
   import sys

   for f in range(1, len(sys.argv)):
     fileName = sys.argv[f]
     file = open(fileName)

     lineCnt = 0
     for line in file:
       lineCnt += 1

     file.close()

     print('File "{0}" contains {1} line{2}'.format(fileName,
                                                   lineCnt,
                                                   " " if lineCnt == 1 else "s"))
   -----------------------------------------------------------------------------

4. a. Write a program that counts words in a file (or multiple files,
      if you prefer). Use the same split() and len() you used in lesson 2.
   -----------------------------------------------------------------------------
   #!/usr/bin/python3
   #============================================================================
   # Description:
   #   Count number of words in 1 or more files.
   #
   # Usage: ./mywordcounter FILE...
   #
   #   Where: FILE is a valid file name for your system. An IOError will be
   #          raised if file not found at this time.
   #
   # Revisions (v1.3):
   #   2011.07.11 - 1.3 Count words.
   #   2011.07.11 - 1.2 Handle multiple files.
   #   2011.07.11 - 1.0 Handle a single file.
   #============================================================================
   #!/usr/bin/python3
   import sys

   for f in range(1, len(sys.argv)):
     fileName = sys.argv[f]
     file = open(fileName)

     wordCnt = 0
     for line in file:
       wordCnt += len(line.split(" "))

     file.close()

     print('File "{0}" contains {1} word{2}'.format(fileName,
                                                    wordCnt,
                                                    " " if wordCnt == 1 else "s"))
   -----------------------------------------------------------------------------

   b. Compare the number of words from your program to what wc -w gives.
      (If you're on a platform that doesn't have wc, run it on a small
      file and count by hand.) Are the answers the same?
   -----------------------------------------------------------------------------
   No.
   -----------------------------------------------------------------------------

   c. Here's the debugging part: why aren't they the same?
   -----------------------------------------------------------------------------
   mywordcounter counted `blank lines` and `multiple spaces` as words and
   `wc -w` did not.

   For example print(line.split(" ")) produced:
     ['\n']
     ['', '', '', '#==#\n']
   -----------------------------------------------------------------------------

   d. OPTIONAL, harder: fix the problems and make your word count
      program give the same answer as wc -w.
   -----------------------------------------------------------------------------
   #!/usr/bin/python3
   #============================================================================
   # Description:
   #   Count number of words in 1 or more files. Compare to `wc -w`.
   #
   # Usage: ./mywordcounter FILE...
   #
   #   Where: FILE is a valid file name for your system. An IOError will be
   #          raised if file not found at this time. 
   #
   # Note:
   #  01. See: help(line.strip)
   #  02. See: dir(re); help(re.sub)
   #  03. See: help("FILES"), help("try") or help("with") (v3)
   #
   # Revisions (v1.4):
   #   2011.07.11 - 1.4 Remove extra spaces and blank lines from count.
   #   2011.07.11 - 1.3 Count words.
   #   2011.07.11 - 1.2 Handle multiple files.
   #   2011.07.11 - 1.0 Handle a single file.
   #============================================================================
   import sys
   import re

   for f in range(1, len(sys.argv)):
     fileName = sys.argv[f]
     file = open(fileName)

     wordCnt = 0
     for line in file:

       line = re.sub(r"'", "", line)      # Replace hypenated words
       line = line.strip()                # Remove lead/trail whitespace
       line = re.sub(r"\s\s+", " ", line) # Replace other multiple spaces

       if line:
         wordCnt += len(line.split(" "))
 
     file.close()

     print('File "{0}" contains {1} word{2}'.format(fileName,
                                                    wordCnt,
                                                    " " if wordCnt == 1 else "s"))
   -----------------------------------------------------------------------------

Thanks,
  Peggy Russell


More information about the Courses mailing list