Difference between revisions of "CSC111 Lab 7 2015b"

From dftwiki3
Jump to: navigation, search
(Created page with "--~~~~ ---- <br /> =Preparation= <br /> * Copy paste the program below in a new Idle window, and call it '''lab5Companion.py'''. * Save your new program to your working dire...")
 
Line 4: Line 4:
 
=Preparation=
 
=Preparation=
 
<br />
 
<br />
* Copy paste the program below in a new Idle window, and call it '''lab5Companion.py'''.   
+
* Copy paste the program below in a new Idle window, and call it '''lab7Companion.py'''.   
 
* Save your new program to your working directory, where you normally save your lab programs.
 
* Save your new program to your working directory, where you normally save your lab programs.
 
* Run the program.  It should create 3 text files in your folder.  You will be using them in this lab.  The files are called:
 
* Run the program.  It should create 3 text files in your folder.  You will be using them in this lab.  The files are called:
Line 13: Line 13:
 
<br />
 
<br />
 
::<source lang="python">
 
::<source lang="python">
# lab5Companion.py
+
# lab7Companion.py
 
# D. Thiebaut
 
# D. Thiebaut
 
# This program will create several files in the directory
 
# This program will create several files in the directory
Line 73: Line 73:
 
<br />
 
<br />
 
* Long strings that span several lines can be created by enclosing them in triple quotes; either triple single-quotes ('''), or triple double-quotes (""").   
 
* Long strings that span several lines can be created by enclosing them in triple quotes; either triple single-quotes ('''), or triple double-quotes (""").   
* Copy/paste the program below in a new program.  You may call it '''lab5.py'''
+
* Copy/paste the program below in a new program.  You may call it '''lab7.py'''
 
<br />
 
<br />
 
::<source lang="python">
 
::<source lang="python">
# lab5.py
+
# lab7.py
  
 
text = """Chocolate
 
text = """Chocolate
Line 207: Line 207:
 
=Reading Text From File=
 
=Reading Text From File=
 
<br />
 
<br />
* Open '''Finder''' or '''Windows Explorer''' and go to the folder that contains your '''lab5.py''' program, as well as your '''lab5Companion.py''' programs.  Make sure the folder contains the 3 text files you created earlier.   
+
* Open '''Finder''' or '''Windows Explorer''' and go to the folder that contains your '''lab7.py''' program, as well as your '''lab7Companion.py''' programs.  Make sure the folder contains the 3 text files you created earlier.   
 
* Open the file name '''hargitay.txt'''.  Verify that it contains the same poem we have been playing with.
 
* Open the file name '''hargitay.txt'''.  Verify that it contains the same poem we have been playing with.
 
* Either create a new program or add a new '''main()''' function to your existing program (rename the original main, '''main2()''', maybe?), and put the code below in the new function:
 
* Either create a new program or add a new '''main()''' function to your existing program (rename the original main, '''main2()''', maybe?), and put the code below in the new function:
Line 291: Line 291:
 
<br />
 
<br />
 
* Open Finder or Windows Explorer, and take a look at the file "hargitay.txt", either with '''TextEdit''' or with '''Notepad'''.  See anything different?
 
* Open Finder or Windows Explorer, and take a look at the file "hargitay.txt", either with '''TextEdit''' or with '''Notepad'''.  See anything different?
* BTW, You can recreate the original file by running the '''lab5Companion.py''' program again.
+
* BTW, You can recreate the original file by running the '''lab7Companion.py''' program again.
 
<br />
 
<br />
 
<br />
 
<br />
Line 311: Line 311:
 
==Moodle Submission==
 
==Moodle Submission==
 
<br />
 
<br />
Rename your program '''lab5_7.py''', and submit your solution program for Challenge #7 to Moodle, in the Lab 5 PB 7 section.
+
Rename your program '''lab7_7.py''', and submit your solution program for Challenge #7 to Moodle, in the Lab 7 PB 7 section.
 
<br />
 
<br />
 
<br />
 
<br />

Revision as of 15:15, 17 October 2015

--D. Thiebaut (talk) 16:13, 17 October 2015 (EDT)



Preparation


  • Copy paste the program below in a new Idle window, and call it lab7Companion.py.
  • Save your new program to your working directory, where you normally save your lab programs.
  • Run the program. It should create 3 text files in your folder. You will be using them in this lab. The files are called:
    • chocoQuotes.txt
    • hargitay.txt
    • joanneHarris.txt


# lab7Companion.py
# D. Thiebaut
# This program will create several files in the directory
# where you will run it.
# The files are retrieved from a Web server, stored temporarily
# in a string, and stored in a local file on your disk.
# The 3 files are very, very short.
# Their names are:
# - chocoQuotes.txt
# - hargitay.txt
# - joanneHarris.txt

import urllib.request  # the lib that handles the url stuff

# main program
def main():

    # list of files to retrieve 
    fileNames = [ "chocoQuotes.txt", "hargitay.txt", "joanneHarris.txt" ]

    # get each file, one at a time
    for fileName in fileNames:

        # url where the files are located
        url = "http://cs.smith.edu/~dthiebaut/111/files/" + fileName

        # fetch the file and put its contents in the
        # string text.
        response = urllib.request.urlopen( url )
        text     = response.read().decode( 'UTF-8' )
        
        # write text to file, in the same directory as this program.
        file     = open( fileName, "w" )
        file.write( text + "\n" )
        file.close()

        # give feedback to user.
        print( "File {0:1} created in your folder".format( fileName ) )


main()



<showafterdate after="20150225 11:00" before="20150601 00:00">

Although this lab has only 2 Moodle submissions, make sure you work on all the challenges. If you skip them, you are only making it harder for you to learn Python and making future challenges that much harder. A little bit of effort regularly beats a huge effort later! The Moodle submissions are due on 2/27 at 11:00 a.m. (morning, just before class). Hope you enjoy this lab!



Splitting Long Strings


In this section you will see how to take text represented as a multi-line string, and process it various ways.


  • Long strings that span several lines can be created by enclosing them in triple quotes; either triple single-quotes (), or triple double-quotes (""").
  • Copy/paste the program below in a new program. You may call it lab7.py


# lab7.py

text = """Chocolate
Chocolate is the first luxury.
It has so many things wrapped up in it:
Deliciousness in the moment,
childhood memories,
and that grin-inducing
feeling of getting a reward for being good.
--Mariska Hargitay"""

def main():
    # make sure main knows that this variable exists
    global text
    
    # split the long string into individual lines
    lines = text.split( "\n" )

    # print each line
    for line in lines:
        print( line )

main()


  • Run the program. Verify that it outputs the entirety of the text.
  • Just to make sure we understand what the variable lines contain, make your program print lines, with a simple print( lines ) statement.
  • Observe that it's just a regular Python list.



Challenge #1

QuestionMark1.jpg
  • Modify your program, and make it print the poem so that each line is centered in a field of 60 spaces. You must use the text variable, and print its line. Do not create a new version of the poem!
  • Expected output


                         Chocolate                          
               Chocolate is the first luxury.               
          It has so many things wrapped up in it:           
                Deliciousness in the moment,                 
                    childhood memories,                     
                   and that grin-inducing                   
        feeling of getting a reward for being good.         
                     --Mariska Hargitay




Challenge #2

QuestionMark2.jpg
  • Make your program print the first line of the poem, centered, but also in uppercase.
  • Make it display the other lines centered, without changing their case.
  • Expected output


                         CHOCOLATE                          
               Chocolate is the first luxury.               
          It has so many things wrapped up in it:           
                Deliciousness in the moment,                 
                    childhood memories,                     
                   and that grin-inducing                   
        feeling of getting a reward for being good.         
                     --Mariska Hargitay



Challenge #3

QuestionMark3.jpg
  • One more modification. Now make your program print the last line right-justified in a field of 60 spaces.
  • The first line is still in upper-case.
  • Make it display the other lines centered, without changing their case.
  • Expected output


                         CHOCOLATE                          
               Chocolate is the first luxury.               
          It has so many things wrapped up in it:           
                Deliciousness in the moment,                 
                    childhood memories,                     
                   and that grin-inducing                   
        feeling of getting a reward for being good.         
                                          --Mariska Hargitay



Challenge #4

QuestionMark4.jpg
  • Make your program print the poem in a box. The top and bottom lines have 50 dashes in them.
  • Expected output


+--------------------------------------------------+
|                    CHOCOLATE                     |
|          Chocolate is the first luxury.          |
|     It has so many things wrapped up in it:      |
|           Deliciousness in the moment,            |
|               childhood memories,                |
|              and that grin-inducing              |
|   feeling of getting a reward for being good.    |
|                                --Mariska Hargitay|
+--------------------------------------------------+



Reading Text From File


  • Open Finder or Windows Explorer and go to the folder that contains your lab7.py program, as well as your lab7Companion.py programs. Make sure the folder contains the 3 text files you created earlier.
  • Open the file name hargitay.txt. Verify that it contains the same poem we have been playing with.
  • Either create a new program or add a new main() function to your existing program (rename the original main, main2(), maybe?), and put the code below in the new function:


def main():
    fileName = "hargitay.txt"
    file = open( fileName, "r" )
    lines = file.readlines()
    file.close()

    for line in lines:
        print( line )
  • Run the program. Observe its output.
  • The reason for the double-spacing is that each line read from the file contains a '\n' at the end of it. And when you print such a line, the print() function adds its own \n at the end. This is why you get a blank line in between lines.
  • One way to remove the '\n' at the end of each line is to print the line as follows: print( line.rstrip() ). The rstrip() method right-strips the string of all white-space characters, which include spaces, tabs, and '\n'-characters.



Challenge #5

QuestionMark5.jpg
  • Make your program get the name of the file from the user, with an input() statement.
  • Then, make your program output the contents of the file in a box, as you did in Challenge 4.
  • Test your program by providing it with different file names:
    • hargitay.txt
    • joanneHarris.txt
    • chocoQuotes.txt
  • Adjust the width of the box if necessary.



Challenge #6

QuestionMark6.jpg
  • Exact same challenge as Challenge 5, but this time start with this program, where I have replaced the .readlines() method with .read().


def main():
    fileName = input( "File name? " )
    file = open( fileName, "r" )
    text = file.read()
    file.close()

    print( "The type of text is", type( text ) )
    print( "text = ", text )


Note
when Python says that something is of type <class 'str'>, it means that it is a string.



Writing Text to File


  • Try this new version of main:


def main():
    fileName = "hargitay.txt"
    file = open( fileName, "r" )
    text = file.read()
    file.close()
    
    text = text.replace( "chocolate", "carrot" )
    text = text.replace( "Chocolate", "Carrot" )

    file = open( fileName, "w" )
    file.write( text + "\n" )
    file.close()


  • Open Finder or Windows Explorer, and take a look at the file "hargitay.txt", either with TextEdit or with Notepad. See anything different?
  • BTW, You can recreate the original file by running the lab7Companion.py program again.




Challenge #7

QuestionMark7.jpg
  • Modify the program so that it prompts the user for
    • The name of the file to read from and write to, and
    • a word
and make the program read the file, replace the word chocolate in it with the word the user picked, and save the resulting text back to the file.
  • Verify that your program works correctly, and that it modifies the file you select and replaces chocolate with the word you choose.


Moodle Submission


Rename your program lab7_7.py, and submit your solution program for Challenge #7 to Moodle, in the Lab 7 PB 7 section.