85 Pages

ch10

Course: CS 177, Fall 2010
School: Purdue
Rating:
 
 
 
 
 

Word Count: 4538

Document Preview

10: Creating Chapter and Modifying Text 1 2 Text Text is the universal medium We can convert any other media to a text representation. We can convert between media formats using text. Text is simple. Like sound, text is usually processed in an arraya long line of characters We refer to one of these long line of characters as a string. In many (especially older) programming languages, text is actually...

Register Now

Unformatted Document Excerpt

Coursehero >> Indiana >> Purdue >> CS 177

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
10: Creating Chapter and Modifying Text 1 2 Text Text is the universal medium We can convert any other media to a text representation. We can convert between media formats using text. Text is simple. Like sound, text is usually processed in an arraya long line of characters We refer to one of these long line of characters as a string. In many (especially older) programming languages, text is actually manipulated as arrays of characters. Its horrible! Python actually knows how to deal with strings. 3 Strings Strings are defined with quote marks. Python actually supports three kinds of quotes: >>> print 'this is a string' this is a string >>> print "this is a string" this is a string >>> print """this is a string""" this is a string Use the right one that allows you to embed quote marks you want >>> aSingleQuote = " ' >>> print aSingleQuote ' " 4 Why would you want to use triple quotes? To have long quotations with returns and such inside them. >>> print aLongString() This is a long string >>> def aLongString(): return """This is a long string""" 5 Encodings for strings Strings are just arrays of characters In most cases, characters are just single bytes. The ASCII encoding standard maps between single byte values and the corresponding characters More recently, characters are two bytes. Unicode uses two bytes per characters so that there are encodings for glyphs (characters) of other languages Java uses Unicode. The version of Python we are using is based in Java, so our strings are actually using Unicode. 6 ASCII encoding through ord() >>> str = "Hello" >>> for char in str: ... print ord(char) ... 72 101 108 108 111 7 There are more characters than we can type Our keyboards dont have all the characters available to us, and its hard to type others into strings. Backspace Return We use backslash escapes to get other characters into strings 8 Backslash escapes \b is backspace \n is a newline (like pressing the Enter key) \t is a tab \uXXXX is a Unicode character, where XXXX is a code and each X can be 0-9 or A-F. http://www.unicode.org/charts/ Must precede the string with u for Unicode to work 9 Testing strings >>> print "hello\tthere\nMark" hello there Mark >>> print u"\uFEED" >>> print u"\u03F0" >>> print "This is\na test" This is a test 10 Manipulating strings We can add strings and get their lengths using the kinds of programming features weve seen previously. >>> hello = "Hello" >>> print len(hello) 5 >>> mark = ", Mark" >>> print len(mark) 6 >>> print hello+mark Hello, Mark >>> print len(hello+mark) 11 11 Getting parts of strings We use the square bracket [] notation to get parts of strings. string[n] gives you the nth character in the string string[n:m] gives you the nth up to (but not including) the mth character. string[0:len(string)] is the whole string 12 Getting parts of strings >>> hello = "Hello" >>> print hello[1] e >>> print hello[0] H >>> print hello[2:4] ll H e l l o 0 1 2 3 4 13 Start and end assumed if not there >>> print hello Hello >>> print hello[:3] Hel >>> print hello[3:] lo >>> print hello[:] Hello 14 Dot notation All data in Python are actually objects Objects not only store data, but they respond to special functions that only objects of the same type understand. We call these special functions methods Methods are functions known only to certain objects To execute a method, you use dot notation object.method() 15 Capitalize is a method known only to strings >>> test="this is a test." >>> print test.capitalize() This is a test. >>> print capitalize(test) #not a function! A local or global name could not be found. NameError: capitalize >>> print 'this is another test'.capitalize() This is another test >>> print 12.capitalize() #12 is not a string! A syntax error is contained in the code -- I can't read it as Python. 16 Useful string methods startswith(prefix) returns true if the string starts with the given suffix endswith(suffix) returns true if the string ends with the given suffix find(findstring) and find(findstring,start) and find(findstring,start,end) finds the findstring in the object string and returns the index number where the string starts. You can tell it what index number to start from, and even where to stop looking. It returns -1 if it fails. There is also rfind(findstring) (and variations) that searches from the end of the string toward the front. 17 Demonstrating startswith >>> letter = "Mr. Mark Guzdial requests the pleasure of your company..." >>> print letter.startswith("Mr.") Python uses 0 1 as false and 1 >>> print letter.startswith("Mrs.") as true 0 18 Demonstrating endswith >>> filename="barbara.jpg" >>> if filename.endswith(".jpg"): ... print "It's a picture" ... It's a picture 19 Demonstrating find >>> print letter Mr. Mark Guzdial requests the pleasure of your company... >>> print letter.find("Mark") 4 >>> print letter.find("Guzdial") 9 >>> print len("Guzdial") 7 >>> print letter[4:9+7] Mark Guzdial >>> print letter.find(Fred") -1 20 Interesting string methods upper() translates the string to uppercase lower() translates the string to lowercase swapcase() makes all upper->lower and vice versa title() makes just the first characters uppercase and the rest lower. isalpha() returns true if the string is not empty and all letters isdigit() returns true if the string is not empty and all numbers 21 Replace method >>> print letter Mr. Mark Guzdial requests the pleasure of your company... >>> letter.replace("a","!") 'Mr. M!rk Guzdi!l requests the ple!sure of your comp!ny...' >>> print letter #it doesnt change letter unless you store the result. Mr. Mark Guzdial requests the pleasure of your company... 22 Strings are sequences >>> for i in "Hello": ... print i ... H e l l o 23 Lists Weve seen lists beforethats what range() returns. Lists are very powerful structures. Lists can contain strings, numbers, even other lists. They work very much like strings You get pieces out with [] You can add lists together You can use for loops on them We can use them to process a variety of kinds of data. 24 Demonstrating lists >>> mylist = ["This","is","a", 12] >>> print mylist ['This', 'is', 'a', 12] >>> print mylist[0] This >>> for i in mylist: ... print i ... This is a 12 >>> print mylist + ["Really!"] ['This', 'is', 'a', 12, 'Really!'] 25 Useful methods to use with lists: But these ones dont work with strings append(something) puts something in the list at the end. remove(something) removes something from the list if its there. sort() puts the list in alphabetical order reverse() reverses the list count(something) tells you the number of times that something is in the list. max() and min() are methods (weve seen them before) that take a list as input and give you the maximum and minimum value in the list. 26 Converting from strings to lists >>> print letter.split(" ") ['Mr.', 'Mark', 'Guzdial', 'requests', 'the', 'pleasure', 'of', 'your', 'company...'] >>>words = letter.split(" ) 27 Extended Split Example def phonebook(): return """ Mary:893-0234:Realtor: Fred:897-2033:Boulder crusher: Barney:234-2342:Professional bowler:""" def findPhone(person): for people in phones(): def phones(): if people[0] == person: phones = phonebook() print "Phone number phonelist = phones.split('\n') for",person,"is",people[1] newphonelist = [] for list in phonelist: newphonelist = newphonelist + [list.split(":")] return newphonelist 28 Running the Phonebook >>> print phonebook() Mary:893-0234:Realtor: Fred:897-2033:Boulder crusher: Barney:234-2342:Professional bowler: >>> print phones() [[''], ['Mary', '893-0234', 'Realtor', ''], ['Fred', '897-2033', 'Boulder crusher', ''], ['Barney', '234-2342', 'Professional bowler', '']] >>> findPhone('Fred') Phone number for Fred is 897-2033 29 Strings have no font Strings are only the characters of text displayed WYSIWYG (What You See is What You Get) WYSIWYG text includes fonts and styles The font is the characteristic look of the letters in all sizes The style is typically the boldface, italics, underline, and other effects applied to the font In printers terms, each style is its own font 30 Encoding font information Font and style information is often encoded as style runs A separate representation from the string Indicates bold, italics, or whatever style modification; start character; and end character. The old brown fox runs. Could be encoded as: "The old brown fox runs." [[bold 0 6] [italics 5 12]] 31 How do we encode all that? Is it a single value? Not really. Do we encode it all in a complex list? We could. How do most text systems handle this? As objects Objects have data, maybe in many parts. Objects know how to act upon their data. Objects methods may be known only to that object, or may be known by many objects, but each object performs that method differently. 32 What can we do with all this? Answer: Just about anything! Strings and lists are about as powerful as one gets in Python By powerful, we mean that we can do a lot of different kinds of computation with them. Examples: Pull up a Web page and grab information out of it, from within a function. Find a nucleotide sequence in a string and print its name. Manipulate functions source But first, we have to learn how to manipulate files 33 Files: Places to put strings and other stuff Files are these named large collections of bytes. Files typically have a base name and a suffix barbara.jpg has a base name of barbara and a suffix of .jpg Files exist in directories (sometimes called folders) Tells us that the file 640x480.jpg is in the folder mediasources in the folder ip-book on the disk C: 34 Directories Directories can contain files or other directories. There is a base directory on your computer, sometimes called the root directory A complete description of what directories to visit to get to your file is called a path 35 We call this structure a tree C:\ C:\ is the root of the tree. It has branches, each of which is a directory Any directory (branch) can contain more directories (branches) and files (leaves) Documents and Settings Windows Mark Guzdial mediasources cs1315 640x480.jpg 36 Why do I care about all this? If youre going to process files, you need to know where they are (directories) and how to specify them (paths). If youre going to do movie processing, which involves lots of files, you need to be able to write programs that process all the files in a directory (or even several directories) without having to write down each and every name of the files. 37 Using lists to represent trees >>> tree = [["Leaf1","Leaf2"],[["Leaf3"], ["Leaf4"],"Leaf5"]] >>> print tree [['Leaf1', 'Leaf2'], [['Leaf3'], ['Leaf4'], 'Leaf5']] >>> print tree[0] ['Leaf1', 'Leaf2'] >>> print tree[1] [['Leaf3'], ['Leaf4'], 'Leaf5'] >>> print tree[1][0] ['Leaf3'] Leaf1 >>> print tree[1][1] ['Leaf4'] >>> print tree[1][2] Leaf5 Leaf5 Leaf3 Leaf2 Leaf4 The Point: Lists allow us to represent complex relationships, like trees 38 How to open a file For reading or writing a file (getting characters out or putting characters in), you need to use open open(filename,how) opens the filename. If you dont provide a full path, the filename is assumed to be in the same directory as JES. how is a two character string that says what you want to do with the string. rt means read text wt means write text rb and wb means read or write bytes We wont do much of that 39 Methods on files: Open returns a file object open() returns a file object that you use to manipulate the file Example: file=open(myfile,wt) file.read() reads the whole file as a single string. file.readlines() reads the whole file into a list where each element is one line. read() and readlines() can only be used once without closing and reopening the file. file.write(something) writes something to the file file.close() closes the filewrites it out to the disk, and wont let you do any more to it without re-opening it. 40 Reading a file >>> program=pickAFile() >>> print program C:\Documents and Settings\Mark Guzdial\My Documents\py-programs\littlepicture.py >>> file=open(program,"rt") >>> contents=file.read() >>> print contents def littlepicture(): canvas=makePicture(getMediaPath("640x480.jpg")) addText(canvas,10,50,"This is not a picture") addLine(canvas,10,20,300,50) addRectFilled(canvas,0,200,300,500,yellow) addRect(canvas,10,210,290,490) return canvas >>> file.close() 41 Reading a file by lines >>> file=open(program,"rt") >>> lines=file.readlines() >>> print lines ['def littlepicture():\n', ' canvas=makePicture(getMediaPath("640x480.jpg"))\n', ' addText(canvas,10,50,"This is not a picture")\n', ' addLine(canvas,10,20,300,50)\n', ' addRectFilled(canvas,0,200,300,500,yellow)\n', ' addRect(canvas,10,210,290,490)\n', ' return canvas'] >>> file.close() 42 Silly example of writing a file >>> writefile = open("myfile.txt","wt") >>> writefile.write("Here is some text.") >>> writefile.write("Here is some more.\n") >>> writefile.write("And now we're done.\n\nTHE END.") >>> writefile.close() >>> writefile=open("myfile.txt","rt") >>> print writefile.read() Here is some text.Here is some more. And now we're done. Notice the \n to make new lines THE END. >>> writefile.close() 43 How you get spam def formLetter(gender ,lastName ,city ,eyeColor ): file = open("formLetter.txt","wt") file.write("Dear ") if gender =="F": file.write("Ms. "+lastName+":\n") if gender =="M": file.write("Mr. "+lastName+":\n") file.write("I am writing to remind you of the offer ") file.write("that we sent to you last week. Everyone in ") file.write(city+" knows what an exceptional offer this is!") file.write("(Especially those with lovely eyes of"+eyeColor+"!)") file.write("We hope to hear from you soon .\n") file.write("Sincerely ,\n") file.write("I.M. Acrook , Attorney at Law") file.close () 44 Trying out our spam generator >>> formLetter("M","Guzdial","Decatur","brown") Dear Mr. Guzdial: I am writing to remind you of the offer that we sent to you last week. Everyone in Decatur knows what an exceptional offer this is!(Especially those with lovely eyes of brown!)We hope to hear from you soon. Sincerely, I.M. Acrook, Attorney at Law Only use this power for good! 45 Writing a program to write programs First, a function that will automatically change the text string that the program littlepicture draws As input, well take a new filename and a new string. Well find() the addText, then look for the first double quote, and then the final double quote. Then well write out the program as a new string to a new file. 46 Changing the little program changeLittle(filename,newstring): # automatically def Get the original file contents programfile=r"C:\Documents and Settings\Mark Guzdial\My Documents\pyprograms\littlepicture.py" file = open(programfile,"rt") contents = file.read() file.close() # Now, find the right place to put our new string addtext = contents.find("addText") firstquote = contents.find('"',addtext) #Double quote after addText endquote = contents.find('"',firstquote+1) #Double quote after firstquote # Make our new file newfile = open(filename,"wt") newfile.write(contents[:firstquote+1]) # Include the quote newfile.write(newstring) newfile.write(contents[endquote:]) newfile.close() 47 changeLittle("sample.py","Here is a sample of changing a program") Original: def littlepicture(): Modified: def littlepicture(): canvas=makePicture(getMediaPath("6 40x480.jpg")) addText(canvas,10,50,"This is not a picture") addLine(canvas,10,20,300,50) canvas=makePicture(getMediaPath("6 40x480.jpg")) addText(canvas,10,50,"Here is a sample of changing a program") addLine(canvas,10,20,300,50) addRectFilled(canvas,0,200,300,500,y ellow) addRect(canvas,10,210,290,490) return canvas addRectFilled(canvas,0,200,300,500,y ellow) addRect(canvas,10,210,290,490) return canvas 48 Thats how vector-based drawing programs work! Editing a line in AutoCAD doesnt change the pixels. It changes the underlying representation of what the line should look like. It then runs the representation and creates the pixels all over again. Is that slower? Who cares? (Refer to Moores Law) 49 Finding data on the Internet The Internet is filled with wonderful data, and almost all of it is in text! Later, well write functions that directly grab files from the Internet, turn them into strings, and pull information out of them. For now, lets assume that the files are on your disk, and lets process them from there. 50 Example: Finding the nucleotide sequence There are places on the Internet where you can grab DNA sequences of things like parasites. What if youre a biologist and want to know if a sequence of nucleotides that you care about is in one of these parasites? We not only want to know yes or no, but which parasite. 51 What the data looks like >Schisto unique AA825099 gcttagatgtcagattgagcacgatgatcgattgaccgtgagatcgacga gatgcgcagatcgagatctgcatacagatgatgaccatagtgtacg >Schisto unique mancons0736 ttctcgctcacactagaagcaagacaatttacactattattattattatt accattattattattattattactattattattattattactattattta ctacgtcgctttttcactccctttattctcaaattgtgtatccttccttt 52 How are we going to do it? First, we get the sequences in a big string. Next, we find where the small subsequence is in the big string. From there, we need to work backwards until we find > which is the beginning of the line with the sequence name. From there, we need to work forwards to the end of the line. From > to the end of the line is the name of the sequence Yes, this is hard to get just right. Lots of debugging prints. 53 The code that does it def findSequence(seq): sequencesFile = getMediaPath("parasites.txt") file = open(sequencesFile,"rt") sequences = file.read() file.close() # Find the sequence seqloc = sequences.find(seq) #print "Found at:",seqloc if seqloc <> -1: # Now, find the ">" with the name of the sequence nameloc = sequences.rfind(">",0,seqloc) # using rfind() here!! #print "Name at:",nameloc endline = sequences.find("\n",nameloc) print "Found in ",sequences[nameloc:endline] if seqloc == -1: print "Not found" 54 Why -1? If .find or .rfind dont find something, they return -1 If they return 0 or more, then its the index of where the search string is found. Whats <>? Thats notation for not equals You can also use != 55 Running the program >>> findSequence("tagatgtcagattgagcacgatgatcgattgacc") Found in >Schisto unique AA825099 >>> findSequence("agtcactgtctggttgaaagtgaatgcttccaccgatt") Found in >Schisto unique mancons0736 56 Example: Get the temperature The weather is always available on the Internet. Can we write a function that takes the current temperature out of a source like http://www.ajc.com/weather or http://www.weather.com? 57 The Internet is mostly text Text is the other unimedia. Web pages are actually text in the format called HTML (HyperText Markup Language) HTML isnt a programming language, its an encoding language. It defines a set of meanings for certain characters, but one cant program in it. We can ignore the HTML meanings for now, and just look at patterns in the text. 58 Wheres the temperature? The word temperature doesnt really show up. But the temperature always follows the word Currently, and always comes before the <b>&deg;</b> <td ><img src="/sharedlocal/weather/images/ps.gif" width="48" height="48" border="0"><font size=2><br></font><font size="-1" face="Arial, Helvetica, sansserif"><b>Currently</b><br> Partly sunny<br> <font size="+2">54<b>&deg;</b></font> <font face="Arial, Helvetica, sansserif" size="+1">F</font></font></td> </tr> 59 We can use the same algorithm weve seen previously Grab the content out of a file in a big string. (Weve saved the HTML page previously. Soon, well see how to grab it directly.) Find the starting indicator (Currently) Find the ending indicator (<b>&deg;) Read the previous characters 60 Finding the temperature def findTemperature(): weatherFile = getMediaPath("ajc-weather.html") file = open(weatherFile,"rt") weather = file.read() file.close() # Find the Temperature curloc = weather.find("Currently") if curloc <> -1: # Now, find the "<b>&deg;" following the temp temploc = weather.find("<b>&deg;",curloc) tempstart = weather.rfind(">",0,temploc) print "Current temperature:",weather[tempstart+1:temploc] if curloc == -1: print "They must have changed the page format -- can't find the temp" 61 Adding new capabilities: Modules What we need to do is to add capabilities to Python that we havent seen so far. We do this by importing external modules. A module is a file with a bunch of additional functions and objects defined within it. Some kind of module capability exists in virtually every programming language. By importing the module, we make the modules capabilities available to our program. Literally, we are using the module, as if wed typed it into our file. 62 Pythons Standard Library Python has an extensive library of modules that come with it. The Python standard library includes modules that allow us to access the Internet, deal with time, generate random numbers, andaccess files in a directory. 63 Accessing pieces of a module We access the additional capabilities of a module using dot notation, after we import the module. How do you know what pieces are there? Check the documentation. Python comes with a Library Guide. There are books like Python Standard Library that describe the modules and provide examples. 64 The OS Module The OS module offers a number of powerful capabilities for dealing with files, e.g., renaming files, finding out when a file was last modified, and so on. We start accessing the OS module by typing: import os The function that knows about directories is listdir(), used as os.listdir() listdir takes a path to a directory as input. 65 Using os.listdir >>> import os >>> print getMediaPath("barbara.jpg") C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\barbara.jpg >>> print getMediaPath("pics") Note: There is no file at C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics >>> print os.listdir("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") ['students1.jpg', 'students2.jpg', 'students5.jpg', 'students6.jpg', 'students7.jpg', 'students8.jpg'] 66 Writing a program to title pictures Well input a directory Well use os.listdir() to get each filename in the directory Well open the file as a picture. Well title it. Well save it out as titled- and the filename. 67 Titling Pictures import os def titleDirectory(dir): for file in os.listdir(dir): picture = makePicture(file) addText(picture,10,10,"This is from My CS CLass") writePictureTo(picture,"titled-"+file) 68 Okay, that didnt work >>> titleDirectory("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") makePicture(filename): There is no file at students1.jpg An error occurred attempting to pass an argument to a function. 69 Why not? Is there a file where we tried to open the picture? Actually, no. Look at the output of os.listdir() again >>> print os.listdir("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") ['students1.jpg', 'students2.jpg', 'students5.jpg', 'students6.jpg', 'students7.jpg', 'students8.jpg'] The strings in the list are just the base names No paths 70 Creating paths If the directory string is in the placeholder variable dir, then dir+file is the full pathname, right? Closeyou still need a path delimiter, like / But its different for each platform! Python gives us a notation that works: // is as a path delimiter for any platform. So: dir+//+file 71 A Working Titling Program import os def titleDirectory(dir): for file in os.listdir(dir): print "Processing:",dir+"//"+file picture = makePicture(dir+"//"+file) addText(picture,10,10,"This is from My CS Class") writePictureTo(picture,dir+"//"+"titled-"+file) 72 Showing it work >>> titleDirectory("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students1.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students2.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students5.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students6.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students7.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students8.jpg >>> print os.listdir("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") ['students1.jpg', 'students2.jpg', 'students5.jpg', 'students6.jpg', 'students7.jpg', 'students8.jpg', 'titledstudents1.jpg', 'titled-students2.jpg', 'titled-students5.jpg', 'titled-students6.jpg', 'titled-students7.jpg', 'titled-students8.jpg'] 73 Inserting a copyright on pictures 74 What if you want to make sure youve got JPEG files? import os def titleDirectory(dir): for file in os.listdir(dir): print "Processing:",dir+"//"+file if file.endswith(".jpg"): picture = makePicture(dir+"//"+file) addText(picture,10,10,"This is from My CS Class") writePictureTo(picture,dir+"//"+"titled-"+file) 75 Say, if thumbs.db is there >>> titleDirectory("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students1.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students2.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students5.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students6.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students7.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//students8.jpg Processing: C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics//Thumbs.db >>> print os.listdir("C:\Documents and Settings\Mark Guzdial\My Documents\mediasources\pics") ['students1.jpg', 'students2.jpg', 'students5.jpg', 'students6.jpg', 'students7.jpg', 'students8.jpg', 'Thumbs.db', 'titled-students1.jpg', 'titled-students2.jpg', 'titled-students5.jpg', 'titled-students6.jpg', 'titled-students7.jpg', 'titled-students8.jpg'] 76 Another interesting module: Random >>> import random >>> for i in range(1,10): ... print random.random() ... 0.8211369314193928 0.6354266779703246 0.9460060163520159 0.904615696559684 0.33500464463254187 0.08124982126940594 0.0711481376807015 0.7255217307346048 0.2920541211845866 77 Randomly choosing words from a list >>> for i in range(1,5): ... print random.choice(["Here", "is", "a", "list", "of", "words", "in","random","order"]) ... list a Here list 78 Randomly generating language Given a list of nouns, verbs that agree in tense and number, and object phrases that all match the verb, We can randomly take one from each to make sentences. 79 Random sentence generator import random def sentence(): nouns = ["Mark", "Adam", "Angela", "Larry", "Jose", "Matt", "Jim"] verbs = ["runs", "skips", "sings", "leaps", "jumps", "climbs", "argues", "giggles"] phrases = ["in a tree", "over a log", "very loudly", "around the bush", "while reading the newspaper"] phrases = phrases + ["very badly", "while skipping","instead of grading", "while typing on the Internet."] print random.choice(nouns), random.choice(verbs), random.choice(phrases) 80 Running the sentence generator >>> sentence() Jose leaps while reading the newspaper >>> sentence() Jim skips while typing on the Internet. >>> sentence() Matt sings very loudly >>> sentence() Adam sings in a tree >>> sentence() Adam sings around the bush >>> sentence() Angela runs while typing on the Internet. >>> sentence() Angela sings around the bush >>> sentence() Jose runs very badly 81 How much smarter can we make this? Can we have different kinds of lists so that, depending on the noun selected, picks the right verb list to get a match in tense and number? How about reading input from the user, picking out key words, then generating an appropriate response? if input.find(mother) <> -1: print Tell me more about your mother 82 Joseph Weizenbaums Eliza Created a program that acted like a therapist. Echoing back to the user whatever they said, as a question. It had rules that triggered on key words in the users statements. It had a little memory of what it had said before. People really believed it was a real therapist! Convinced Weizenbaum of the dangers of computing. 83 Session with the Doctor >>>My mother bothers me. Tell me something about your family. >>>My father was a caterpillar. Note that this is all generated automatically. You seem to dwell on your family. >>>My job isn't good either. Is it because of your plans that you say your job is not good either? 84 Many other Python Standard Libraries datetime and calendar know about dates. What day of the week was the US Declaration of Independence signed? Thursday. math knows about sin() and sqrt() zipfile knows how to make and read .zip files email lets you (really!) build your own spam program, or filter spam, or build an email tool for yourself. SimpleHTTPServer is a complete working Web server. 85
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Purdue - CS - 177
Chapter 11:Advanced Text Techniques: Web and Information12Networks: Two or morecomputers communicatingNetworks are formed when distinct computerscommunicate via some mechanism.Rarely does the communication take the place of 0/1voltages over a wir
Purdue - CS - 177
Chapter 12:Making Text for the Web12HyperText Markup Language(HTML)HTML is a kind of SGML (Standardized General MarkupLanguage) SGML was invented by IBM and others as a way of defining parts of a document.HTML is a simpler form of SGML, but with
Purdue - CS - 177
Chapter 13:Creating and Modifying Movies12Movies, animations, and videooh my!Were going to refer generically to captured (recorded)motion as movies.This includes motion entirely generated by graphicaldrawings, which are normally called animations
Purdue - CS - 177
Chapter 14:Topics in Computer Science: Speed12Big speed differencesMany of the techniques weve learned take no time at allin other applicationsSelect a figure in Word.Its automatically inverted as fast as you can wipe.Color changes in Photoshop h
Purdue - CS - 177
Chapter 15:Topics in Computer Science: Functional Programming12Functions: Whats the point?Why do we have functions?More specifically, why have more than one?And if you have more than one, which ones should youhave?Once I have functions, what can
Purdue - CS - 177
Chapter 16:Topics in Computer Science: Object-OrientedProgramming12History of Objects: Where theycame fromStart of the Story: Late 60's and Early 70'sWindows are made of glass, mice are undesirable rodentsGood programming = Procedural Abstraction
Purdue - CS - 177
CS 177 Fall 2010 Exam I-There are 25 single choice questions. Each one is worth 4 points. The total score for theexam is 100.Answer the questions on the bubble sheet given.Fill in the Instructor, Course, Signature, Test, and Date blanks in the bubble
Purdue - CS - 177
CS 177 Fall 2010 Exam II-There are 25 single choice questions. Each one is worth 4 points. The total score for theexam is 100.Answer the questions on the bubble sheet given.Fill in the Instructor, Course, Signature, Test, and Date blanks in the bubbl
Purdue - CS - 177
CS 177 Fall 2010 Final Exam-There are 50 single choice questions. Each one is worth 4 points. The total score for theexam is 200 points.Answer the questions on the bubble sheet given.Fill in the Instructor, Course, Signature, Test, and Date blanks in
Purdue - CS - 177
Learning Styles and StrategiesLearningWhat is measured is PREFERENCE, notPREFERENCEcompetenceBetter understanding of how you prefer tolearn means a higher quotient for successUnderstanding your preference and that ofothers may help in communicatio
Purdue - CS - 177
Project 1: Sound Editordue Sunday, October 31st, 11:59 pmThis is an individual project.For this project you will develop a simple sound editing program. Background Course Material Setup Project Specification Submitting Your Project Grading Criter
Purdue - CS - 177
PROJECT 2: ADVANCED ADVENTURE GAMEdue Sunday, November 21st, 11:59 pmThis is an individual project.BACKGROUNDIn this project you will modify the Adventure Game by adding new features andfunctions. You will use your knowledge of hierarchal decompositi
Purdue - CS - 177
Project 3: Mastering HTMLThis is a team project to be done in groups of at most 3 studentsProject Due Friday, December 10th, 11:59 pmTA: Mohammad Kazi (mkazi@cs.purdue.edu)Background and Course MaterialSetupProject SpecificationFinal Project Turnin
Purdue - CS - 177
CS 177 Programming withMultimedia ObjectsRecitationCourse Policy On Course WebsiteHow Computer WorksWhat Computers Understand? Computers can only understandEncoding of numbers. So what is the meaning ofEncoding? Figure 3 (pag. 8) of the textboo
Purdue - CS - 177
CS 177 Week 2 Recitation SlidesVariables, Files and Functions1AnnouncementsGet your I-Clickers to class next time.2ANY QUESTIONS?3Table of contentVariablesFilesFunctionsWhat is a function? Why to use a function? How to write a function in JE
Purdue - CS - 177
CS 177 Week 3 Recitation SlidesPictures, Pixels, Colorsandfor Loop1Announcements2ANY QUESTIONS?3Reminder: Why digitize media?Real media is analogue (continuous).To digitize it, we break it into parts and encode them intonumbers.By encoding th
Purdue - CS - 177
CS 177 Week 4 Recitation Slidesfor Loopif statementandrange1AnnouncementsEXAM 1Wednesday 09/296:30p - 7:30pEE 1292ANY QUESTIONS?3Lets remember for Loopdef decreaseRed(picture):for p in getPixels(picture):value = getRed(p)setRed(p,value*0
Purdue - CS - 177
CS 177 Week 5 Recitation SlidesMirroring and copying images,Using for Loop, if statement, and range1AnnouncementsEXAM 1Wednesday 09/296:30p - 7:30pEE 1292ANY QUESTIONS?3Horizontal mirror recipe4mirroring means intuitively &quot;flipping around&quot; a
Purdue - CS - 177
CS 177 Week 6 Recitation SlidesScalingDrawing on imagesVector-based Vs. Bitmap graphical representation1AnnouncementsnEXAM 1Wednesday 09/296:30p - 7:30pEE 1292ScalingnScaling a picture (smaller or larger) has to do withsampling the source p
Purdue - CS - 177
CS 177 Week 7 Recitation SlidesModifying Sounds using Loops+Discussion of some Exam Questions1ANY QUESTIONS?2Q3. Consider the following function definition:def sum(a, b):c=a+breturn cprint Hello WorldWhat is the output when you execute sum(4,5
Purdue - CS - 177
CS 177 Week 8 Recitation SlidesJES Sound functionsandModifying SoundsIncreasing/Decreasing VolumeMaximizing (Normalizing)SplicingReversingMirroring1ANY QUESTIONS?2Lets remember SoundWe store sounds as array of integer values Each value is st
Purdue - CS - 177
CS 177 Week 9 Recitation SlidesSound Combination, SamplingandBuilding Bigger Programs1ANY QUESTIONS?2Media File Path is Important&gt; setMediaPath() #must be called before getMediaPath&gt; c4=makeSound(getMediaPath(&quot;bassoon-c4.wav&quot;)&gt; e4=makeSound(getM
Purdue - CS - 177
CS 177 Week 9 Recitation SlidesCreating and Modifying Text1ANY QUESTIONS?2Text and StringLike sound, text is usually processed in an arraya longline of charactersStrings are defined with quote marks:Single quotes my string Double quotes my strin
Purdue - CS - 177
CS 177 Week 11 Recitation SlidesWriting out programs, Reading from the Internetand Using Modules1ANY QUESTIONS?2Writing a program to writeprogramsFirst, a function that will automatically change the textstring that the program littlepicture draws
Purdue - CS - 177
CS 177 Week 12 Recitation SlidesAdvanced Text Techniques and Making Text for theWeb + (some examII questions)1Q21. Suppose you have the following string:str = &quot;Purdue University&quot;Which of the following statements will produce the same result ofstr.f
Purdue - CS - 177
CS 177 Week 13 Recitation SlidesHTML and Relational Database1ANY QUESTIONS?2What is HTML?Language which specifies the format of the text on theworld wide web.a.k.a. Hyper Text Markup Language.Was originally created with the intent of identifying
Purdue - CS - 177
CS 177 Week 15 Recitation SlidesSpeedBig-O notationSorting and SearchingandFunctions with Recursion1ANY QUESTIONS?2More than one way to solve aproblemTheres always more than one way to solve a problem.3You can walk to one place around the blo
Purdue - CS - 177
CS 177 Week 16 Recitation SlidesObject Oriented Programming1ANY QUESTIONS?2Procedural Abstractions3Define tasks to be performedBreak tasks into smaller and smaller pieces Until you reach an implementable sizeDefine the data to be manipulatedDes
Purdue - CS - 177
Q1. What is the name of the function that will display the names of variables in yourprogram?A)showVars()B)showNames()C)showFiles()D)showObjects()Key: AQ2. The following function will result in a JES error. Why?A)B)C)D)In line 1 the : is m
Purdue - CS - 177
The Concept of Team WorkStarting with Lab 9 you will be doing lab exercises in groups of two or three students. You willalso do projects in groups. The content of this document applies to labs and to projects. Youshould elect one student as the group l
Purdue - CS - 177
Teaming: Reflection Paper GuidelinesPart of a successful teaming experience is the ability to critically reflect on that experience andarticulate it well to others. College-level writing that has been spell-checked and proof read isexpected. This paper
Purdue - CS - 177
If you want to turnin your project from your home you can follow the followingsteps:1. Download the SSH Secure Shell Client 3.2.9. You can google it or find atftp:/ftp.tm.informatik.uni-frankfurt.de/pub/prog/SSHSecureShellClient3.2.9.exeThis program i
University of Sydney - MATH - 1011
Periodic Functions[1.2 of the Notes, Chapter 1 ofStewart is also useful]There are many examples in natureof events repeating themselves overand over again. Nature is periodic!Example 1If you plot the length of day againsttime the graph repeats its
Purdue - HIS - 306
NewFinalExam1.ComparethedifferencesbetweentheEastandWestintermsofinfluencandlandscapearchitecture.StudentResponse:EgyptianlandscapeswemadefertilebytheoverfgardenswereformalandmadelandscapebecausnonaturallandscapestoirrigationsystemswereinEgypti
Purdue - HIS - 306
History of Horticulture: Lecture 1Lecture 1Dating the Past: Geologic,Archeologic, Biologic, and HumanArcheologic,CultureDating the Past (years ago)Dating the Past (years ago)1History of Horticulture: Lecture 1Dating the Past (years ago)The Emer
Purdue - HIS - 306
History of Horticulture: Lecture 2Lecture 2Early Humans and the Prehistoric Record:HumanPlant InteractionDating the PastHuman Fossils &amp; ToolsHominid fossils and tools date to 1.8 million yearsago.There is some evidence of tools in Europe as early
Purdue - HIS - 306
History of Horticulture: Lecture 3Lecture 3Neolithic Revolution and theDiscovery of AgricultureDating the PastThe Great Technological Discoveriesof Pre-historyThe discovery of toolsThe discovery and control of fireThe invention of agricultureThe
Purdue - HIS - 306
History of Horticulture: Lecture 4Lecture 4Geography of Plant DomesticationAlphonse de Candolle (18061893)Charles Darwin (18091882)1858 Origin of SpeciesNicholas Ivanovitch Vavilov (18871943)Alphonse de Candolle (18061893)Alphonse De Candolle as a
Purdue - HIS - 306
History of Horticulture: Lecture 5Lecture 5Centers of Origin of Crop PlantsThe eight Vavilovian Centers of Origin for crop plantsOLD WORLDI. Chinese Center: The largest independent centerwhich includes the mountainous regions of centraland western
Purdue - HIS - 306
NewFinalExam1.ComparethedifferencesbetweentheEastandWestintermsofinfluencandlandscapearchitecture.StudentResponse:EgyptianlandscapeswemadefertilebytheoverfgardenswereformalandmadelandscapebecausnonaturallandscapestoirrigationsystemswereinEgypti
Purdue - HIS - 306
Title:exam1Started:Submitted:Timespent:Totalscore:February21,20088:26AMFebruary21,20088:58AM00:31:4799/100=99% Totalscoreadjustedby0.0Maximumpossiblescore:1001.ToxicsubstancestendtobeeliminatedinStudentResponseValueCorrectAnswer1 cultiva
Purdue - HIS - 306
JumptoNavigationFrameTitle:Started:Submitted:Timespent:Totalscore:exam2March5,200810:31AMMarch5,200811:08AM00:36:5298/100=98% Totalscoreadjustedby0.0Maximumpossiblescore:1001.ComparecontributionsofDioscoridesandTheophrastestohorticulturalkS
Purdue - HIS - 306
Title:Quiz1Started:January15,20088:29PMSubmitted:January15,20088:43PMTimespent:00:13:56Totalscore:10/10=100% Totalscoreadjustedby0.0 Maximumpossiblescore:101.GiveapproximatedatefortheBronzeAgeStudentResponse1. 4,000yearsagoValueCorrectAnswe
Purdue - HIS - 306
Extra Credit AssignmentTwo famous garden scenes of Shakespeare are found in Richard II and The Winter's Tale.Choose one and delineate and discuss the horticultural knowledge revealed in these excerpts.Your submission should be at least one page in leng
Purdue - HIS - 306
ARTGiuseppeArcimboldoMichelangeloCaravaggioGeorgDionysusEhretGeorgiaOKeefeVincentvanGoghLeonardodaVinciBartolomeoMayanYumKaax,Yucatan,Chultunes.AztecsTenochtitlan,Milpas,Chinampas,MexicoCity.IncasMacchuPichu,Potatoculture,.Cuzco.GreeceRhizotomoi,Hippoc
Purdue - HIS - 306
EXAM #1Question Type #1Cultivated Food Plants Toxic Substances tend to be eliminated in Seed dormancy is lost in Self pollination tends to increase in Fruit and organ size is greater in Life span for crops grown for vegetative organs is increased i
Purdue - HIS - 306
Yourlocation:AssessmentsViewAllSubmissionsViewAttemptViewAttempt1of1Title:exam1Started:Submitted:Timespent:Totalscore:January28,20098:28AMJanuary28,20098:47AM00:18:2190/100=90% Totalscoreadjustedby0.0 Maximumpossiblescore:1001.Toxicsubstance
Purdue - HIS - 306
Yourlocation:AssessmentsViewAllSubmissionsViewAttemptViewAttempt1of1Title:exam2Started: February2,20098:20AMSubmitted: February2,20098:53AMTime00:32:52spent:Total97/100=97% Totalscoreadjustedby0.0 Maximumpossiblescore:100score:1.Comparecontri
Purdue - HORT - 306
Old World Crops: Wheat, rice, Date. Apple, citrus/ New World Crops: Peanut, cacao, maize, squash, tomato Ikebana, Bonsai, and Sakai:ikebana is a Japanese flower arrangement that is based on the symbolic use of flowers. Bonsai is specimen grown on miniatu
Purdue - HORT - 306
View Attempt 1 of 1Title:Started:Submitted:Time spent:New Final ExamDecember 8, 2010 3:02 PMDecember 8, 2010 4:15 PM01:12:34Total score:170/200 = 85% Total score adjusted by 0.0Maximum possible score: 2001.Define the following design termsSy
Purdue - HORT - 306
Title:NewFinalExamStarted:Submitted:Timespent:Totalscore:February11,20098:29AMFebruary11,20099:52AM01:23:25154/200=77% Totalscoreadjustedby0.0 Maximumpossiblescore:2001.Defendthefollowingstatementandgiveexamples.&lt;br&gt;Thegreatestcontributiontoho
Purdue - HORT - 306
ViewAttempt1of1Title:Quiz3Started:Submitted:Timespent:Totalscore:January15,200911:31PMJanuary15,200911:40PM00:08:5310/10=100% Totalscoreadjustedby0.0 Maximumpossiblescore:101.WhatisevidenceforplantintroductionintoEgypt?(2points)StudentRespon
Purdue - HORT - 306
Yourlocation:AssessmentsViewAllSubmissionsViewAttemptViewAttempt1of1Title:exam1Started:Submitted:Timespent:Totalscore:January28,20098:28AMJanuary28,20098:47AM00:18:2190/100=90% Totalscoreadjustedby0.0 Maximumpossiblescore:1001.Toxicsubstance
Purdue - HORT - 306
Title:Quiz1Started:January15,20088:29PMSubmitted:January15,20088:43PMTimespent:00:13:56Totalscore:10/10=100% Totalscoreadjustedby0.0 Maximumpossiblescore:101.GiveapproximatedatefortheBronzeAgeStudentResponse1. 4,000yearsagoValueCorrectAnswe
Purdue - HORT - 306
Title:Quiz2Started:Submitted:Timespent:Totalscore:January15,20088:50PMJanuary15,20089:06PM00:16:1110/10=100% Totalscoreadjustedby0.0Maximumpossiblescore:101.WheatoriginatedinStudentResponse1. Americas2.Asia3. AfricaValueCorrectFeedbac
Purdue - HORT - 306
Title:Quiz3Started:Submitted:Timespent:Totalscore:January16,20087:06PMJanuary16,20087:15PM00:09:4310/10=100% Totalscoreadjustedby0.0Maximumpossiblescore:101.WhatisevidenceforplantintroductionintoEgypt?(2points)StudentResponse:SampleCorrectAn
Purdue - HORT - 306
Title:Quiz4Started:Submitted:Timespent:Totalscore:January16,20087:16PMJanuary16,20087:33PM00:16:4510/10=100% Totalscoreadjustedby0.0Maximumpossiblescore:101.Whatisthehorticulturalsignificanceof:HangingGardensofBabylon(2points)StudentResponse
Purdue - HORT - 306
Title:Quiz5Started:Submitted:Timespent:Totalscore:January16,20087:34PMJanuary16,20087:44PM00:09:248/10=80% Totalscoreadjustedby0.0Maximumpossiblescore:101.Definemilpa(1point)StudentResponse:SampleCorrectAnswerAztecmaizefield.Score:Aztecma
Purdue - HORT - 306
Title:Quiz6Started:Submitted:Timespent:Totalscore:January17,20083:30PMJanuary17,20083:54PM00:24:0510/10=100% Totalscoreadjustedby0.0Maximumpossiblescore:101.Identifyanddescribeinrelationtoagricultureorhorticulture.(1point)Aristotle:StudentRe
Purdue - HORT - 306
Title:Quiz7Started:Submitted:Timespent:Totalscore:January17,20083:54PMJanuary17,20084:06PM00:11:5010/10=100% Totalscoreadjustedby0.0Maximumpossiblescore:101.DefineorIdentify.(1point)RaisedBeds:StudentResponse:Bedsthatareraisedandfillewhich
Purdue - HORT - 306
Title:Quiz8Started:Submitted:Timespent:Totalscore:January17,20084:06PMJanuary17,20084:15PM00:09:0510/10=100% Totalscoreadjustedby0.0Maximumpossiblescore:101.Matchthecorrectanswer.(10points)StatementResponseConceptthatthemedicinalqualitiesof