#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    8
    Rep Power
    0

    Analyzing a file with read function?


    I am working on an assignment and am a bit stuck. Here is the problem:

    Write code that takes any of the script you have written during this class and analyzes the contents of the script and output the number of:
    Lines of codes
    Comments
    import statements
    Empty lines
    Print functions
    If-statements
    For-loops and
    While-loops

    Counting the number of lines is easy, but I have no idea how to check for specific statements and such? Your help would be appreciated. Here is what I have so far:

    c = open("nested_loop3.py", "r")
    line_count = 0

    for line in c:
    line_count += 1
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    I think you will find the in operator to be your best friend here.

    To find prints for example:
    Code:
    if "print" in line:
        print_count += 1
    Of course if you want the program to be perfect you would have to make sure that the occurence was not in the context of a comment or string, but I somehow doubt your instructor is wanting that level of sophistication.

    -Mek
    Last edited by Mekire; November 17th, 2013 at 07:20 PM.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    8
    Rep Power
    0
    Originally Posted by Mekire
    I think you will find the in operator to be your best friend here.

    To find prints for example:
    Code:
    if "print" in line:
        print_count += 1
    Of course if you want the program to be perfect you would have to make sure that the occurence was not in the context of a comment or string, but I somehow doubt your instructor is wanting that level of sophistication.

    -Mek
    I forgot about the in operator. Of course! Thank you Mek.

IMN logo majestic logo threadwatch logo seochat tools logo