id
int64
0
25.6k
text
stringlengths
0
4.59k
6,500
strings [ [ [ [ [ [ figure string indexes getting the length of string using len len is built-in function that returns the number of characters in stringfruit 'bananalen(fruit to get the last letter of stringyou might be tempted to try something like thislength len(fruitlast fruit[lengthindexerrorstring index out of range the reason for the indexerror is that there is no letter in "bananawith the index since we started counting at zerothe six letters are numbered to to get the last characteryou have to subtract from lengthlast fruit[length- print(lasta alternativelyyou can use negative indiceswhich count backward from the end of the string the expression fruit[- yields the last letterfruit[- yields the second to lastand so on traversal through string with loop lot of computations involve processing string one character at time often they start at the beginningselect each character in turndo something to itand continue until the end this pattern of processing is called traversal one way to write traversal is with while loopindex while index len(fruit)letter fruit[indexprint(letterindex index
6,501
this loop traverses the string and displays each letter on line by itself the loop condition is index len(fruit)so when index is equal to the length of the stringthe condition is falseand the body of the loop is not executed the last character accessed is the one with the index len(fruit)- which is the last character in the string exercise write while loop that starts at the last character in the string and works its way backwards to the first character in the stringprinting each letter on separate lineexcept backwards another way to write traversal is with for loopfor char in fruitprint(chareach time through the loopthe next character in the string is assigned to the variable char the loop continues until no characters are left string slices segment of string is called slice selecting slice is similar to selecting characters 'monty pythonprint( [ : ]monty print( [ : ]python the operator returns the part of the string from the " -thcharacter to the " -thcharacterincluding the first but excluding the last if you omit the first index (before the colon)the slice starts at the beginning of the string if you omit the second indexthe slice goes to the end of the stringfruit 'bananafruit[: 'banfruit[ :'anaif the first index is greater than or equal to the second the result is an empty stringrepresented by two quotation marksfruit 'bananafruit[ : 'an empty string contains no characters and has length but other than thatit is the same as any other string exercise given that fruit is stringwhat does fruit[:mean
6,502
strings strings are immutable it is tempting to use the operator on the left side of an assignmentwith the intention of changing character in string for examplegreeting 'helloworld!greeting[ 'jtypeerror'strobject does not support item assignment the "objectin this case is the string and the "itemis the character you tried to assign for nowan object is the same thing as valuebut we will refine that definition later an item is one of the values in sequence the reason for the error is that strings are immutablewhich means you can' change an existing string the best you can do is create new string that is variation on the originalgreeting 'helloworld!new_greeting 'jgreeting[ :print(new_greetingjelloworldthis example concatenates new first letter onto slice of greeting it has no effect on the original string looping and counting the following program counts the number of times the letter "aappears in stringword 'bananacount for letter in wordif letter =' 'count count print(countthis program demonstrates another pattern of computation called counter the variable count is initialized to and then incremented each time an "ais found when the loop exitscount contains the resultthe total number of ' exercise encapsulate this code in function named countand generalize it so that it accepts the string and the letter as arguments
6,503
the in operator the word in is boolean operator that takes two strings and returns true if the first appears as substring in the second'ain 'bananatrue 'seedin 'bananafalse string comparison the comparison operators work on strings to see if two strings are equalif word ='banana'print('all rightbananas 'other comparison operations are useful for putting words in alphabetical orderif word 'banana'print('your word,word 'comes before banana 'elif word 'banana'print('your word,word 'comes after banana 'elseprint('all rightbananas 'python does not handle uppercase and lowercase letters the same way that people do all the uppercase letters come before all the lowercase letterssoyour wordpineapplecomes before banana common way to address this problem is to convert strings to standard formatsuch as all lowercasebefore performing the comparison keep that in mind in case you have to defend yourself against man armed with pineapple string methods strings are an example of python objects an object contains both data (the actual string itselfand methodswhich are effectively functions that are built into the object and are available to any instance of the object python has function called dir which lists the methods available for an object the type function shows the type of an object and the dir function shows the available methods
6,504
strings stuff 'hello worldtype(stuffdir(stuff['capitalize''casefold''center''count''encode''endswith'expandtabs''find''format''format_map''index'isalnum''isalpha''isdecimal''isdigit''isidentifier'islower''isnumeric''isprintable''isspace'istitle''isupper''join''ljust''lower''lstrip'maketrans''partition''replace''rfind''rindex'rjust''rpartition''rsplit''rstrip''split'splitlines''startswith''strip''swapcase''title'translate''upper''zfill'help(str capitalizehelp on method_descriptorcapitalizes capitalize(-str return capitalized version of si make the first character have upper case and the rest lower case while the dir function lists the methodsand you can use help to get some simple documentation on methoda better source of documentation for string methods would be calling method is similar to calling function (it takes arguments and returns valuebut the syntax is different we call method by appending the method name to the variable name using the period as delimiter for examplethe method upper takes string and returns new string with all uppercase lettersinstead of the function syntax upper(word)it uses the method syntax word upper(word 'banananew_word word upper(print(new_wordbanana this form of dot notation specifies the name of the methodupperand the name of the string to apply the method toword the empty parentheses indicate that this method takes no argument method call is called an invocationin this casewe would say that we are invoking upper on the word for examplethere is string method named find that searches for the position of one string within another
6,505
word 'bananaindex word find(' 'print(index in this examplewe invoke find on word and pass the letter we are looking for as parameter the find method can find substrings as well as charactersword find('na' it can take as second argument the index where it should startword find('na' one common task is to remove white space (spacestabsor newlinesfrom the beginning and end of string using the strip methodline here we go line strip('here we gosome methods such as startswith return boolean values line 'have nice dayline startswith('have'true line startswith(' 'false you will note that startswith requires case to matchso sometimes we take line and map it all to lowercase before we do any checking using the lower method line 'have nice dayline startswith(' 'false line lower('have nice dayline lower(startswith(' 'true in the last examplethe method lower is called and then we use startswith to see if the resulting lowercase string starts with the letter "has long as we are careful with the orderwe can make multiple method calls in single expression
6,506
strings exercise there is string method called count that is similar to the function in the previous exercise read the documentation of this method atwrite an invocation that counts the number of times the letter occurs in "banana parsing strings oftenwe want to look into string and find substring for example if we were presented series of lines formatted as followsfrom stephen marquarduct ac za sat jan : : and we wanted to pull out only the second half of the address ( uct ac zafrom each linewe can do this by using the find method and string slicing firstwe will find the position of the at-sign in the string then we will find the position of the first space after the at-sign and then we will use string slicing to extract the portion of the string which we are looking for data 'from stephen marquard@uct ac za sat jan atpos data find('@'print(atpos sppos data find(',atposprint(sppos host data[atpos+ :spposprint(hostuct ac za : : we use version of the find method which allows us to specify position in the string where we want find to start looking when we slicewe extract the characters from "one beyond the at-sign through up to but not including the space characterthe documentation for the find method is available at format operator the format operatorallows us to construct stringsreplacing parts of the strings with the data stored in variables when applied to integersis the modulus operator but when the first operand is stringis the format operator the first operand is the format stringwhich contains one or more format sequences that specify how the second operand is formatted the result is string
6,507
for examplethe format sequence % means that the second operand should be formatted as an integer ("dstands for "decimal")camels '%dcamels ' the result is the string ' 'which is not to be confused with the integer value format sequence can appear anywhere in the stringso you can embed value in sentencecamels ' have spotted % camels camels ' have spotted camels if there is more than one format sequence in the stringthe second argument has to be tuple each format sequence is matched with an element of the tuplein order the following example uses % to format an integer% to format floating-point number (don' ask why)and % to format string'in % years have spotted % % ( 'camels''in years have spotted camels the number of elements in the tuple must match the number of format sequences in the string the types of the elements also must match the format sequences'% % % ( typeerrornot enough arguments for format string '% 'dollarstypeerror% formata number is requirednot str in the first examplethere aren' enough elementsin the secondthe element is the wrong type the format operator is powerfulbut it can be difficult to use you can read more about it at debugging skill that you should cultivate as you program is always asking yourself"what could go wrong here?or alternatively"what crazy thing might our user do to crash our (seeminglyperfect program?for examplelook at the program which we used to demonstrate the while loop in the on iteration tuple is sequence of comma-separated values inside pair of parenthesis we will cover tuples in
6,508
strings while trueline input(''if line[ ='#'continue if line ='done'break print(lineprint('done!'codelook what happens when the user enters an empty line of inputhello there hello there don' print this print thisprint thistraceback (most recent call last)file "copytildone py"line in if line[ ='#'indexerrorstring index out of range the code works fine until it is presented an empty line then there is no zero-th characterso we get traceback there are two solutions to this to make line three "safeeven if the line is empty one possibility is to simply use the startswith method which returns false if the string is empty if line startswith('#')another way is to safely write the if statement using the guardian pattern and make sure the second logical expression is evaluated only where there is at least one character in the string if len(line and line[ ='#' glossary counter variable used to count somethingusually initialized to zero and then incremented empty string string with no characters and length represented by two quotation marks format operator an operator%that takes format string and tuple and generates string that includes the elements of the tuple formatted as specified by the format string
6,509
format sequence sequence of characters in format stringlike %dthat specifies how value should be formatted format string stringused with the format operatorthat contains format sequences flag boolean variable used to indicate whether condition is true or false invocation statement that calls method immutable the property of sequence whose items cannot be assigned index an integer value used to select an item in sequencesuch as character in string item one of the values in sequence method function that is associated with an object and called using dot notation object something variable can refer to for nowyou can use "objectand "valueinterchangeably search pattern of traversal that stops when it finds what it is looking for sequence an ordered setthat isa set of values where each value is identified by an integer index slice part of string specified by range of indices traverse to iterate through the items in sequenceperforming similar operation on each exercises exercise take the following python code that stores stringstr ' -dspam-confidence: use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into floating point number exercise read the documentation of the string methods at you might want to experiment with some of them to make sure you understand how they work strip and replace are particularly useful the documentation uses syntax that might be confusing for examplein find(sub[start[end]])the brackets indicate optional arguments so sub is requiredbut start is optionaland if you include startthen end is optional
6,510
strings
6,511
files persistence so farwe have learned how to write programs and communicate our intentions to the central processing unit using conditional executionfunctionsand iterations we have learned how to create and use data structures in the main memory the cpu and memory are where our software works and runs it is where all of the "thinkinghappens but if you recall from our hardware architecture discussionsonce the power is turned offanything stored in either the cpu or main memory is erased so up to nowour programs have just been transient fun exercises to learn python what nextsoftware input and output devices central processing unit network main memory secondary memory figure secondary memory in this we start to work with secondary memory (or filessecondary memory is not erased when the power is turned off or in the case of usb flash drivethe data we write from our programs can be removed from the system and transported to another system
6,512
files we will primarily focus on reading and writing text files such as those we create in text editor later we will see how to work with database files which are binary filesspecifically designed to be read and written through database software opening files when we want to read or write file (say on your hard drive)we first must open the file opening the file communicates with your operating systemwhich knows where the data for each file is stored when you open fileyou are asking the operating system to find the file by name and make sure the file exists in this examplewe open the file mbox txtwhich should be stored in the same folder that you are in when you start python you can download this file from www py com/code /mbox txt fhand open('mbox txt'print(fhandif the open is successfulthe operating system returns us file handle the file handle is not the actual data contained in the filebut instead it is "handlethat we can use to read the data you are given handle if the requested file exists and you have the proper permissions to read the file open close read write your program from stephen return-path< datesat jan tosource@coll fromstephen subject[sakaidetailshttp:figure file handle if the file does not existopen will fail with traceback and you will not get handle to access the contents of the filefhand open('stuff txt'traceback (most recent call last)file ""line in filenotfounderror[errno no such file or directory'stuff txtlater we will use try and except to deal more gracefully with the situation where we attempt to open file that does not exist
6,513
text files and lines text file can be thought of as sequence of linesmuch like python string can be thought of as sequence of characters for examplethis is sample of text file which records mail activity from various individuals in an open source project development teamfrom stephen marquard@uct ac za sat jan : : return-pathdatesat jan : : - tosource@collab sakaiproject org fromstephen marquard@uct ac za subject[sakaisvn commitr content/branchesdetailsthe entire file of mail interactions is available from www py com/code /mbox txt and shortened version of the file is available from www py com/code /mbox-short txt these files are in standard format for file containing multiple mail messages the lines which start with "fromseparate the messages and the lines which start with "from:are part of the messages for more information about the mbox formatsee to break the file into linesthere is special character that represents the "end of the linecalled the newline character in pythonwe represent the newline character as backslash- in string constants even though this looks like two charactersit is actually single character when we look at the variable by entering "stuffin the interpreterit shows us the \ in the stringbut when we use print to show the stringwe see the string broken into two lines by the newline character stuff 'hello\nworld!stuff 'hello\nworld!print(stuffhello worldstuff ' \nyprint(stuffx len(stuff you can also see that the length of the string \ny is three characters because the newline character is single character
6,514
files so when we look at the lines in filewe need to imagine that there is special invisible character called the newline at the end of each line that marks the end of the line so the newline character separates the characters in the file into lines reading files while the file handle does not contain the data for the fileit is quite easy to construct for loop to read through and count each of the lines in filefhand open('mbox-short txt'count for line in fhandcount count print('line count:'countcodewe can use the file handle as the sequence in our for loop our for loop simply counts the number of lines in the file and prints them out the rough translation of the for loop into english is"for each line in the file represented by the file handleadd one to the count variable the reason that the open function does not read the entire file is that the file might be quite large with many gigabytes of data the open statement takes the same amount of time regardless of the size of the file the for loop actually causes the data to be read from the file when the file is read using for loop in this mannerpython takes care of splitting the data in the file into separate lines using the newline character python reads each line through the newline and includes the newline as the last character in the line variable for each iteration of the for loop because the for loop reads the data one line at timeit can efficiently read and count the lines in very large files without running out of main memory to store the data the above program can count the lines in any size file using very little memory since each line is readcountedand then discarded if you know the file is relatively small compared to the size of your main memoryyou can read the whole file into one string using the read method on the file handle fhand open('mbox-short txt'inp fhand read(print(len(inp) print(inp[: ]from stephen marquar in this examplethe entire contents (all , charactersof the file mbox-short txt are read directly into the variable inp we use string slicing to print out the first characters of the string data stored in inp
6,515
when the file is read in this mannerall the characters including all of the lines and newline characters are one big string in the variable inp it is good idea to store the output of read as variable because each call to read exhausts the resourcefhand open('mbox-short txt'print(len(fhand read()) print(len(fhand read()) remember that this form of the open function should only be used if the file data will fit comfortably in the main memory of your computer if the file is too large to fit in main memoryyou should write your program to read the file in chunks using for or while loop searching through file when you are searching through data in fileit is very common pattern to read through fileignoring most of the lines and only processing lines which meet particular condition we can combine the pattern for reading file with string methods to build simple search mechanisms for exampleif we wanted to read file and only print out lines which started with the prefix "from:"we could use the string method startswith to select only those lines with the desired prefixfhand open('mbox-short txt'count for line in fhandif line startswith('from:')print(linecodewhen this program runswe get the following outputfromstephen marquard@uct ac za fromlouis@media berkeley edu fromzqian@umich edu fromrjlowe@iupui edu the output looks great since the only lines we are seeing are those which start with "from:"but why are we seeing the extra blank linesthis is due to that invisible newline character each of the lines ends with newlineso the print statement
6,516
files prints the string in the variable line which includes newline and then print adds another newlineresulting in the double spacing effect we see we could use line slicing to print all but the last characterbut simpler approach is to use the rstrip method which strips whitespace from the right side of string as followsfhand open('mbox-short txt'for line in fhandline line rstrip(if line startswith('from:')print(linecodewhen this program runswe get the following outputfromstephen marquard@uct ac za fromlouis@media berkeley edu fromzqian@umich edu fromrjlowe@iupui edu fromzqian@umich edu fromrjlowe@iupui edu fromcwen@iupui edu as your file processing programs get more complicatedyou may want to structure your search loops using continue the basic idea of the search loop is that you are looking for "interestinglines and effectively skipping "uninterestinglines and then when we find an interesting linewe do something with that line we can structure the loop to follow the pattern of skipping uninteresting lines as followsfhand open('mbox-short txt'for line in fhandline line rstrip(skip 'uninteresting linesif not line startswith('from:')continue process our 'interestingline print(linecodethe output of the program is the same in englishthe uninteresting lines are those which do not start with "from:"which we skip using continue for the "interestinglines ( those that start with "from:"we perform the processing on those lines we can use the find string method to simulate text editor search that finds lines where the search string is anywhere in the line since find looks for an occurrence
6,517
of string within another string and either returns the position of the string or - if the string was not foundwe can write the following loop to show lines which contain the string "@uct ac za( they come from the university of cape town in south africa)fhand open('mbox-short txt'for line in fhandline line rstrip(if line find('@uct ac za'=- continue print(linecodewhich produces the following outputfrom stephen marquard@uct ac za sat jan : : -authentication-warningset sender to stephen marquard@uct ac za using - fromstephen marquard@uct ac za authorstephen marquard@uct ac za from david horwitz@uct ac za fri jan : : -authentication-warningset sender to david horwitz@uct ac za using - fromdavid horwitz@uct ac za authordavid horwitz@uct ac za here we also use the contracted form of the if statement where we put the continue on the same line as the if this contracted form of the if functions the same as if the continue were on the next line and indented letting the user choose the file name we really do not want to have to edit our python code every time we want to process different file it would be more usable to ask the user to enter the file name string each time the program runs so they can use our program on different files without changing the python code this is quite simple to do by reading the file name from the user using input as followsfname input('enter the file name'fhand open(fnamecount for line in fhandif line startswith('subject:')count count print('there were'count'subject lines in'fnamecode
6,518
files we read the file name from the user and place it in variable named fname and open that file now we can run the program repeatedly on different files python search py enter the file namembox txt there were subject lines in mbox txt python search py enter the file namembox-short txt there were subject lines in mbox-short txt before peeking at the next sectiontake look at the above program and ask yourself"what could go possibly wrong here?or "what might our friendly user do that would cause our nice little program to ungracefully exit with tracebackmaking us look not-so-cool in the eyes of our users? using tryexceptand open told you not to peek this is your last chance what if our user types something that is not file namepython search py enter the file namemissing txt traceback (most recent call last)file "search py"line in fhand open(fnamefilenotfounderror[errno no such file or directory'missing txtpython search py enter the file namena na boo boo traceback (most recent call last)file "search py"line in fhand open(fnamefilenotfounderror[errno no such file or directory'na na boo boodo not laugh users will eventually do every possible thing they can do to break your programseither on purpose or with malicious intent as matter of factan important part of any software development team is person or group called quality assurance (or qa for shortwhose very job it is to do the craziest things possible in an attempt to break the software that the programmer has created the qa team is responsible for finding the flaws in programs before we have delivered the program to the end users who may be purchasing the software or paying our salary to write the software so the qa team is the programmer' best friend so now that we see the flaw in the programwe can elegantly fix it using the try/except structure we need to assume that the open call might fail and add recovery code when the open fails as follows
6,519
fname input('enter the file name'tryfhand open(fnameexceptprint('file cannot be opened:'fnameexit(count for line in fhandif line startswith('subject:')count count print('there were'count'subject lines in'fnamecodethe exit function terminates the program it is function that we call that never returns now when our user (or qa teamtypes in silliness or bad file nameswe "catchthem and recover gracefullypython search py enter the file namembox txt there were subject lines in mbox txt python search py enter the file namena na boo boo file cannot be openedna na boo boo protecting the open call is good example of the proper use of try and except in python program we use the term "pythonicwhen we are doing something the "python waywe might say that the above example is the pythonic way to open file once you become more skilled in pythonyou can engage in repartee with other python programmers to decide which of two equivalent solutions to problem is "more pythonicthe goal to be "more pythoniccaptures the notion that programming is part engineering and part art we are not always interested in just making something workwe also want our solution to be elegant and to be appreciated as elegant by our peers writing files to write fileyou have to open it with mode "was second parameterfout open('output txt'' 'print(foutif the file already existsopening it in write mode clears out the old data and starts freshso be carefulif the file doesn' exista new one is created
6,520
files the write method of the file handle object puts data into the filereturning the number of characters written the default write mode is text for writing (and readingstrings line "this here' the wattle,\nfout write(line againthe file object keeps track of where it isso if you call write againit adds the new data to the end we must make sure to manage the ends of lines as we write to the file by explicitly inserting the newline character when we want to end line the print statement automatically appends newlinebut the write method does not add the newline automatically line 'the emblem of our land \nfout write(line when you are done writingyou have to close the file to make sure that the last bit of data is physically written to the disk so it will not be lost if the power goes off fout close(we could close the files which we open for read as wellbut we can be little sloppy if we are only opening few files since python makes sure that all open files are closed when the program ends when we are writing fileswe want to explicitly close the files so as to leave nothing to chance debugging when you are reading and writing filesyou might run into problems with whitespace these errors can be hard to debug because spacestabsand newlines are normally invisibles ' \ \ print( the built-in function repr can help it takes any object as an argument and returns string representation of the object for stringsit represents whitespace characters with backslash sequencesprint(repr( )' \ \
6,521
this can be helpful for debugging one other problem you might run into is that different systems use different characters to indicate the end of line some systems use newlinerepresented \ others use return characterrepresented \ some use both if you move files between different systemsthese inconsistencies might cause problems for most systemsthere are applications to convert from one format to another you can find them (and read more about this issueat orof courseyou could write one yourself glossary catch to prevent an exception from terminating program using the try and except statements newline special character used in files and strings to indicate the end of line pythonic technique that works elegantly in python "using try and except is the pythonic way to recover from missing filesquality assurance person or team focused on insuring the overall quality of software product qa is often involved in testing product and identifying problems before the product is released text file sequence of characters stored in permanent storage like hard drive exercises exercise write program to read through file and print the contents of the file (line by lineall in upper case executing the program will look as followspython shout py enter file namembox-short txt from stephen marquard@uct ac za sat jan : : return-pathreceivedfrom murder (mail umich edu ]by frankenstein mail umich edu (cyrus vwith lmtpasat jan : : - you can download the file from www py com/code /mbox-short txt exercise write program to prompt for file nameand then read through the file and look for lines of the formx-dspam-confidence when you encounter line that starts with " -dspam-confidence:pull apart the line to extract the floating-point number on the line count these lines and then compute the total of the spam confidence
6,522
files values from these lines when you reach the end of the fileprint out the average spam confidence enter the file namembox txt average spam confidence enter the file namembox-short txt average spam confidence test your file on the mbox txt and mbox-short txt files exercise sometimes when programmers get bored or want to have bit of funthey add harmless easter egg to their program modify the program that prompts the user for the file name so that it prints funny message when the user types in the exact file name "na na boo boothe program should behave normally for all other files which exist and don' exist here is sample execution of the programpython egg py enter the file namembox txt there were subject lines in mbox txt python egg py enter the file namemissing tyxt file cannot be openedmissing tyxt python egg py enter the file namena na boo boo na na boo boo to you you have been punk'dwe are not encouraging you to put easter eggs in your programsthis is just an exercise
6,523
lists list is sequence like stringa list is sequence of values in stringthe values are charactersin listthey can be any type the values in list are called elements or sometimes items there are several ways to create new listthe simplest is to enclose the elements in square brackets ("[and "]")[ ['crunchy frog''ram bladder''lark vomit'the first example is list of four integers the second is list of three strings the elements of list don' have to be the same type the following list contains stringa floatan integerand (lo!another list['spam' [ ] list within another list is nested list that contains no elements is called an empty listyou can create one with empty brackets[as you might expectyou can assign list values to variablescheeses ['cheddar''edam''gouda'numbers [ empty [print(cheesesnumbersempty['cheddar''edam''gouda'[ [
6,524
lists lists are mutable the syntax for accessing the elements of list is the same as for accessing the characters of stringthe bracket operator the expression inside the brackets specifies the index remember that the indices start at print(cheeses[ ]cheddar unlike stringslists are mutable because you can change the order of items in list or reassign an item in list when the bracket operator appears on the left side of an assignmentit identifies the element of the list that will be assigned numbers [ numbers[ print(numbers[ the one-th element of numberswhich used to be is now you can think of list as relationship between indices and elements this relationship is called mappingeach index "maps toone of the elements list indices work the same way as string indicesany integer expression can be used as an index if you try to read or write an element that does not existyou get an indexerror if an index has negative valueit counts backward from the end of the list the in operator also works on lists cheeses ['cheddar''edam''gouda''edamin cheeses true 'briein cheeses false traversing list the most common way to traverse the elements of list is with for loop the syntax is the same as for stringsfor cheese in cheesesprint(cheese
6,525
this works well if you only need to read the elements of the list but if you want to write or update the elementsyou need the indices common way to do that is to combine the functions range and lenfor in range(len(numbers))numbers[inumbers[ this loop traverses the list and updates each element len returns the number of elements in the list range returns list of indices from to where is the length of the list each time through the loopi gets the index of the next element the assignment statement in the body uses to read the old value of the element and to assign the new value for loop over an empty list never executes the bodyfor in emptyprint('this never happens 'although list can contain another listthe nested list still counts as single element the length of this list is four['spam' ['brie''roquefort''pol le veq'][ ] list operations the operator concatenates listsa [ [ print( [ similarlythe operator repeats list given number of times[ [ [ [ the first example repeats four times the second example repeats the list three times
6,526
lists list slices the slice operator also works on listst [' '' '' '' '' '' ' [ : [' '' ' [: [' '' '' '' ' [ :[' '' '' 'if you omit the first indexthe slice starts at the beginning if you omit the secondthe slice goes to the end so if you omit boththe slice is copy of the whole list [:[' '' '' '' '' '' 'since lists are mutableit is often useful to make copy before performing operations that foldspindleor mutilate lists slice operator on the left side of an assignment can update multiple elementst [' '' '' '' '' '' ' [ : [' '' 'print( [' '' '' '' '' '' ' list methods python provides methods that operate on lists for exampleappend adds new element to the end of listt [' '' '' ' append(' 'print( [' '' '' '' 'extend takes list as an argument and appends all of the elementst [' '' '' ' [' '' ' extend( print( [' '' '' '' '' 'this example leaves unmodified sort arranges the elements of the list from low to high
6,527
[' '' '' '' '' ' sort(print( [' '' '' '' '' 'most list methods are voidthey modify the list and return none if you accidentally write sort()you will be disappointed with the result deleting elements there are several ways to delete elements from list if you know the index of the element you wantyou can use popt [' '' '' ' pop( print( [' '' 'print(xb pop modifies the list and returns the element that was removed if you don' provide an indexit deletes and returns the last element if you don' need the removed valueyou can use the del statementt [' '' '' 'del [ print( [' '' 'if you know the element you want to remove (but not the index)you can use removet [' '' '' ' remove(' 'print( [' '' 'the return value from remove is none to remove more than one elementyou can use del with slice indext [' '' '' '' '' '' 'del [ : print( [' '' 'as usualthe slice selects all the elements up tobut not includingthe second index
6,528
lists lists and functions there are number of built-in functions that can be used on lists that allow you to quickly look through list without writing your own loopsnums [ print(len(nums) print(max(nums) print(min(nums) print(sum(nums) print(sum(nums)/len(nums) the sum(function only works when the list elements are numbers the other functions (max()len()etc work with lists of strings and other types that can be comparable we could rewrite an earlier program that computed the average of list of numbers entered by the user using list firstthe program to compute an average without listtotal count while (true)inp input('enter number'if inp ='done'break value float(inptotal total value count count average total count print('average:'averagecodein this programwe have count and total variables to keep the number and running total of the user' numbers as we repeatedly prompt the user for number we could simply remember each number as the user entered it and use built-in functions to compute the sum and count at the end numlist list(while (true)inp input('enter number'if inp ='done'break value float(inp
6,529
numlist append(valueaverage sum(numlistlen(numlistprint('average:'averagecodewe make an empty list before the loop startsand then each time we have numberwe append it to the list at the end of the programwe simply compute the sum of the numbers in the list and divide it by the count of the numbers in the list to come up with the average lists and strings string is sequence of characters and list is sequence of valuesbut list of characters is not the same as string to convert from string to list of charactersyou can use lists 'spamt list(sprint( [' '' '' '' 'because list is the name of built-in functionyou should avoid using it as variable name also avoid the letter "lbecause it looks too much like the number " so that' why use "tthe list function breaks string into individual letters if you want to break string into wordsyou can use the split methods 'pining for the fjordst split(print( ['pining''for''the''fjords'print( [ ]the once you have used split to break the string into list of wordsyou can use the index operator (square bracketto look at particular word in the list you can call split with an optional argument called delimiter that specifies which characters to use as word boundaries the following example uses hyphen as delimiters 'spam-spam-spamdelimiter '- split(delimiter['spam''spam''spam'
6,530
lists join is the inverse of split it takes list of strings and concatenates the elements join is string methodso you have to invoke it on the delimiter and pass the list as parametert ['pining''for''the''fjords'delimiter delimiter join( 'pining for the fjordsin this case the delimiter is space characterso join puts space between words to concatenate strings without spacesyou can use the empty string""as delimiter parsing lines usually when we are reading file we want to do something to the lines other than just printing the whole line often we want to find the "interesting linesand then parse the line to find some interesting part of the line what if we wanted to print out the day of the week from those lines that start with "from"from stephen marquard@uct ac za sat jan : : the split method is very effective when faced with this kind of problem we can write small program that looks for lines where the line starts with "from"split those linesand then print out the third word in the linefhand open('mbox-short txt'for line in fhandline line rstrip(if not line startswith('from ')continue words line split(print(words[ ]codethe program produces the following outputsat fri fri fri laterwe will learn increasingly sophisticated techniques for picking the lines to work on and how we pull those lines apart to find the exact bit of information we are looking for
6,531
objects and values if we execute these assignment statementsa 'bananab 'bananawe know that and both refer to stringbut we don' know whether they refer to the same string there are two possible statesa 'bananaa 'bananab 'bananafigure variables and objects in one casea and refer to two different objects that have the same value in the second casethey refer to the same object to check whether two variables refer to the same objectyou can use the is operator 'bananab 'bananaa is true in this examplepython only created one string objectand both and refer to it but when you create two listsyou get two objectsa [ [ is false in this case we would say that the two lists are equivalentbecause they have the same elementsbut not identicalbecause they are not the same object if two objects are identicalthey are also equivalentbut if they are equivalentthey are not necessarily identical until nowwe have been using "objectand "valueinterchangeablybut it is more precise to say that an object has value if you execute [ , , ] refers to list object whose value is particular sequence of elements if another list has the same elementswe would say it has the same value
6,532
lists aliasing if refers to an object and you assign athen both variables refer to the same objecta [ is true the association of variable with an object is called reference in this examplethere are two references to the same object an object with more than one reference has more than one nameso we say that the object is aliased if the aliased object is mutablechanges made with one alias affect the otherb[ print( [ although this behavior can be usefulit is error-prone in generalit is safer to avoid aliasing when you are working with mutable objects for immutable objects like stringsaliasing is not as much of problem in this examplea 'bananab 'bananait almost never makes difference whether and refer to the same string or not list arguments when you pass list to functionthe function gets reference to the list if the function modifies list parameterthe caller sees the change for exampledelete_head removes the first element from listdef delete_head( )del [ here' how it is usedletters [' '' '' 'delete_head(lettersprint(letters[' '' '
6,533
the parameter and the variable letters are aliases for the same object it is important to distinguish between operations that modify lists and operations that create new lists for examplethe append method modifies listbut the operator creates new listt [ append( print( [ print( none [ print( [ is false this difference is important when you write functions that are supposed to modify lists for examplethis function does not delete the head of listdef bad_delete_head( ) [ :wrongthe slice operator creates new list and the assignment makes refer to itbut none of that has any effect on the list that was passed as an argument an alternative is to write function that creates and returns new list for exampletail returns all but the first element of listdef tail( )return [ :this function leaves the original list unmodified here' how it is usedletters [' '' '' 'rest tail(lettersprint(rest[' '' 'exercise write function called chop that takes list and modifies itremoving the first and last elementsand returns none then write function called middle that takes list and returns new list that contains all but the first and last elements
6,534
lists debugging careless use of lists (and other mutable objectscan lead to long hours of debugging here are some common pitfalls and ways to avoid them don' forget that most list methods modify the argument and return none this is the opposite of the string methodswhich return new string and leave the original alone if you are used to writing string code like thisword word strip(it is tempting to write list code like thist sort(wrongbecause sort returns nonethe next operation you perform with is likely to fail before using list methods and operatorsyou should read the documentation carefully and then test them in interactive mode the methods and operators that lists share with other sequences (like stringsare documented atdocs python org/library/stdtypes html#common-sequence-operations the methods and operators that only apply to mutable sequences are documented atdocs python org/library/stdtypes html#mutable-sequence-types pick an idiom and stick with it part of the problem with lists is that there are too many ways to do things for exampleto remove an element from listyou can use popremovedelor even slice assignment to add an elementyou can use the append method or the operator but don' forget that these are rightt append(xt [xand these are wrongt append([ ] append(xt [xt wrongwrongwrongwrongtry out each of these examples in interactive mode to make sure you understand what they do notice that only the last one causes runtime errorthe other three are legalbut they do the wrong thing make copies to avoid aliasing if you want to use method like sort that modifies the argumentbut you need to keep the original list as wellyou can make copy
6,535
orig [: sort(in this example you could also use the built-in function sortedwhich returns newsorted list and leaves the original alone but in that case you should avoid using sorted as variable name listssplitand files when we read and parse filesthere are many opportunities to encounter input that can crash our program so it is good idea to revisit the guardian pattern when it comes writing programs that read through file and look for "needle in the haystacklet' revisit our program that is looking for the day of the week on the from lines of our filefrom stephen marquard@uct ac za sat jan : : since we are breaking this line into wordswe could dispense with the use of startswith and simply look at the first word of the line to determine if we are interested in the line at all we can use continue to skip lines that don' have "fromas the first word as followsfhand open('mbox-short txt'for line in fhandwords line split(if words[ !'fromcontinue print(words[ ]this looks much simpler and we don' even need to do the rstrip to remove the newline at the end of the file but is it betterpython search py sat traceback (most recent call last)file "search py"line in if words[ !'fromcontinue indexerrorlist index out of range it kind of works and we see the day from the first line (sat)but then the program fails with traceback error what went wrongwhat messed-up data caused our elegantcleverand very pythonic program to failyou could stare at it for long time and puzzle through it or ask someone for helpbut the quicker and smarter approach is to add print statement the best place to add the print statement is right before the line where the program failed and print out the data that seems to be causing the failure now this approach may generate lot of lines of outputbut at least you will immediately have some clue as to the problem at hand so we add print of the variable words right before line five we even add prefix "debug:to the line so we can keep our regular output separate from our debug output
6,536
lists for line in fhandwords line split(print('debug:'wordsif words[ !'fromcontinue print(words[ ]when we run the programa lot of output scrolls off the screen but at the endwe see our debug output and the traceback so we know what happened just before the traceback debug[' -dspam-confidence:'' 'debug[' -dspam-probability:'' 'debug[traceback (most recent call last)file "search py"line in if words[ !'fromcontinue indexerrorlist index out of range each debug line is printing the list of words which we get when we split the line into words when the program failsthe list of words is empty [if we open the file in text editor and look at the fileat that point it looks as followsx-dspam-resultinnocent -dspam-processedsat jan : : -dspam-confidence -dspam-probability detailsthe error occurs when our program encounters blank lineof course there are "zero wordson blank line why didn' we think of that when we were writing the codewhen the code looks for the first word (word[ ]to check to see if it matches "from"we get an "index out of rangeerror this of course is the perfect place to add some guardian code to avoid checking the first word if the first word is not there there are many ways to protect this codewe will choose to check the number of words we have before we look at the first wordfhand open('mbox-short txt'count for line in fhandwords line split(print('debug:'wordsif len(words= continue if words[ !'fromcontinue print(words[ ]first we commented out the debug print statement instead of removing itin case our modification fails and we need to debug again then we added guardian statement that checks to see if we have zero wordsand if sowe use continue to skip to the next line in the file
6,537
we can think of the two continue statements as helping us refine the set of lines which are "interestingto us and which we want to process some more line which has no words is "uninterestingto us so we skip to the next line line which does not have "fromas its first word is uninteresting to us so we skip it the program as modified runs successfullyso perhaps it is correct our guardian statement does make sure that the words[ will never failbut perhaps it is not enough when we are programmingwe must always be thinking"what might go wrong?exercise figure out which line of the above program is still not properly guarded see if you can construct text file which causes the program to fail and then modify the program so that the line is properly guarded and test it to make sure it handles your new text file exercise rewrite the guardian code in the above example without two if statements insteaduse compound logical expression using the or logical operator with single if statement glossary aliasing circumstance where two or more variables refer to the same object delimiter character or string used to indicate where string should be split element one of the values in list (or other sequence)also called items equivalent having the same value index an integer value that indicates an element in list identical being the same object (which implies equivalencelist sequence of values list traversal the sequential accessing of each element in list nested list list that is an element of another list object something variable can refer to an object has type and value reference the association between variable and its value exercises exercise find all unique words in file shakespeare used over , words in his works but how would you determine thathow would you produce the list of all the words that shakespeare usedwould you download all his workread it and track all unique words by handlet' use python to achieve that instead list all unique wordssorted in alphabetical orderthat are stored in file romeo txt containing subset of shakespeare' work to get starteddownload copy of the file www py com/code /romeo txt create list of unique wordswhich will contain the final result write program to open the file romeo txt and read it line by line for each
6,538
lists linesplit the line into list of words using the split function for each wordcheck to see if the word is already in the list of unique words if the word is not in the list of unique wordsadd it to the list when the program completessort and print the list of unique words in alphabetical order enter fileromeo txt ['arise''but''it''juliet''who''already''and''breaks''east''envious''fair''grief''is''kill''light''moon''pale''sick''soft''sun''the''through''what''window''with''yonder'exercise minimalist email client mbox (mail boxis popular file format to store and share collection of emails this was used by early email servers and desktop apps without getting into too many detailsmbox is text filewhich stores emails consecutively emails are separated by special line which starts with from (notice the spaceimportantlylines starting with from(notice the colondescribes the email itself and does not act as separator imagine you wrote minimalist email appthat lists the email of the senders in the user' inbox and counts the number of emails write program to read through the mail box data and when you find line that starts with "from"you will split the line into words using the split function we are interested in who sent the messagewhich is the second word on the from line from stephen marquard@uct ac za sat jan : : you will parse the from line and print out the second word for each from linethen you will also count the number of from (not from:lines and print out count at the end this is good sample output with few lines removedpython fromcount py enter file namembox-short txt stephen marquard@uct ac za louis@media berkeley edu zqian@umich edu some output removed ray@media berkeley edu cwen@iupui edu cwen@iupui edu cwen@iupui edu there were lines in the file with from as the first word exercise rewrite the program that prompts the user for list of numbers and prints out the maximum and minimum of the numbers at
6,539
the end when the user enters "donewrite the program to store the numbers the user enters in list and use the max(and min(functions to compute the maximum and minimum numbers after the loop completes enter number enter number enter number enter number enter number enter numberdone maximum minimum
6,540
lists
6,541
dictionaries dictionary is like listbut more general in listthe index positions have to be integersin dictionarythe indices can be (almostany type you can think of dictionary as mapping between set of indices (which are called keysand set of values each key maps to value the association of key and value is called key-value pair or sometimes an item as an examplewe'll build dictionary that maps from english to spanish wordsso the keys and the values are all strings the function dict creates new dictionary with no items because dict is the name of built-in functionyou should avoid using it as variable name eng sp dict(print(eng sp{the curly brackets{}represent an empty dictionary to add items to the dictionaryyou can use square bracketseng sp['one''unothis line creates an item that maps from the key 'oneto the value "unoif we print the dictionary againwe see key-value pair with colon between the key and valueprint(eng sp{'one''uno'this output format is also an input format for exampleyou can create new dictionary with three items but if you print eng spyou might be surprisedeng sp {'one''uno''two''dos''three''tres'print(eng sp{'one''uno''three''tres''two''dos'
6,542
dictionaries the order of the key-value pairs is not the same in factif you type the same example on your computeryou might get different result in generalthe order of items in dictionary is unpredictable but that' not problem because the elements of dictionary are never indexed with integer indices insteadyou use the keys to look up the corresponding valuesprint(eng sp['two']'dosthe key 'twoalways maps to the value "dosso the order of the items doesn' matter if the key isn' in the dictionaryyou get an exceptionprint(eng sp['four']keyerror'fourthe len function works on dictionariesit returns the number of key-value pairslen(eng sp the in operator works on dictionariesit tells you whether something appears as key in the dictionary (appearing as value is not good enough'onein eng sp true 'unoin eng sp false to see whether something appears as value in dictionaryyou can use the method valueswhich returns the values as type that can be converted to listand then use the in operatorvals list(eng sp values()'unoin vals true the in operator uses different algorithms for lists and dictionaries for listsit uses linear search algorithm as the list gets longerthe search time gets longer in direct proportion to the length of the list for dictionariespython uses an algorithm called hash table that has remarkable propertythe in operator takes about the same amount of time no matter how many items there are in dictionary won' explain why hash functions are so magicalbut you can read more about it at wikipedia org/wiki/hash_table exercise download copy of the file www py com/code /words txt write program that reads the words in words txt and stores them as keys in dictionary it doesn' matter what the values are then you can use the in operator as fast way to check whether string is in the dictionary
6,543
dictionary as set of counters suppose you are given string and you want to count how many times each letter appears there are several ways you could do it you could create variablesone for each letter of the alphabet then you could traverse the string andfor each characterincrement the corresponding counterprobably using chained conditional you could create list with elements then you could convert each character to number (using the built-in function ord)use the number as an index into the listand increment the appropriate counter you could create dictionary with characters as keys and counters as the corresponding values the first time you see characteryou would add an item to the dictionary after that you would increment the value of an existing item each of these options performs the same computationbut each of them implements that computation in different way an implementation is way of performing computationsome implementations are better than others for examplean advantage of the dictionary implementation is that we don' have to know ahead of time which letters appear in the string and we only have to make room for the letters that do appear here is what the code might look likeword 'brontosaurusd dict(for in wordif not in dd[ elsed[cd[ print(dwe are effectively computing histogramwhich is statistical term for set of counters (or frequenciesthe for loop traverses the string each time through the loopif the character is not in the dictionarywe create new item with key and the initial value (since we have seen this letter onceif is already in the dictionary we increment [chere' the output of the program{' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' the histogram indicates that the letters "aand "bappear once"oappears twiceand so on dictionaries have method called get that takes key and default value if the key appears in the dictionaryget returns the corresponding valueotherwise it returns the default value for example
6,544
dictionaries counts 'chuck 'annie 'jan' print(counts get('jan' ) print(counts get('tim' ) we can use get to write our histogram loop more concisely because the get method automatically handles the case where key is not in dictionarywe can reduce four lines down to one and eliminate the if statement word 'brontosaurusd dict(for in wordd[cd get( , print(dthe use of the get method to simplify this counting loop ends up being very commonly used "idiomin python and we will use it many times in the rest of the book so you should take moment and compare the loop using the if statement and in operator with the loop using the get method they do exactly the same thingbut one is more succinct dictionaries and files one of the common uses of dictionary is to count the occurrence of words in file with some written text let' start with very simple file of words taken from the text of romeo and juliet for the first set of exampleswe will use shortened and simplified version of the text with no punctuation later we will work with the text of the scene with punctuation included but soft what light through yonder window breaks it is the east and juliet is the sun arise fair sun and kill the envious moon who is already sick and pale with grief we will write python program to read through the lines of the filebreak each line into list of wordsand then loop through each of the words in the line and count each word using dictionary you will see that we have two for loops the outer loop is reading the lines of the file and the inner loop is iterating through each of the words on that particular line this is an example of pattern called nested loops because one of the loops is the outer loop and the other loop is the inner loop because the inner loop executes all of its iterations each time the outer loop makes single iterationwe think of the inner loop as iterating "more quicklyand the outer loop as iterating more slowly the combination of the two nested loops ensures that we will count every word on every line of the input file
6,545
fname input('enter the file name'tryfhand open(fnameexceptprint('file cannot be opened:'fnameexit(counts dict(for line in fhandwords line split(for word in wordsif word not in countscounts[word elsecounts[word+ print(countscodein our else statementwe use the more compact alternative for incrementing variable counts[word+ is equivalent to counts[wordcounts[word either method can be used to change the value of variable by any desired amount similar alternatives exist for -=*=and /when we run the programwe see raw dump of all of the counts in unsorted hash order (the romeo txt file is available at www py com/code /romeo txtpython count py enter the file nameromeo txt {'and' 'envious' 'already' 'fair' 'is' 'through' 'pale' 'yonder' 'what' 'sun' 'who' 'but' 'moon' 'window' 'sick' 'east' 'breaks' 'grief' 'with' 'light' 'it' 'arise' 'kill' 'the' 'soft' 'juliet' it is bit inconvenient to look through the dictionary to find the most common words and their countsso we need to add some more python code to get us the output that will be more helpful looping and dictionaries if you use dictionary as the sequence in for statementit traverses the keys of the dictionary this loop prints each key and the corresponding valuecounts 'chuck 'annie 'jan' for key in countsprint(keycounts[key]
6,546
dictionaries here' what the output looks likejan chuck annie againthe keys are in no particular order we can use this pattern to implement the various loop idioms that we have described earlier for example if we wanted to find all the entries in dictionary with value above tenwe could write the following codecounts 'chuck 'annie 'jan' for key in countsif counts[key print(keycounts[key]the for loop iterates through the keys of the dictionaryso we must use the index operator to retrieve the corresponding value for each key here' what the output looks likejan annie we see only the entries with value above if you want to print the keys in alphabetical orderyou first make list of the keys in the dictionary using the keys method available in dictionary objectsand then sort that list and loop through the sorted listlooking up each key and printing out key-value pairs in sorted order as followscounts 'chuck 'annie 'jan' lst list(counts keys()print(lstlst sort(for key in lstprint(keycounts[key]here' what the output looks like['jan''chuck''annie'annie chuck jan first you see the list of keys in unsorted order that we get from the keys method then we see the key-value pairs in order from the for loop
6,547
advanced text parsing in the above example using the file romeo txtwe made the file as simple as possible by removing all punctuation by hand the actual text has lots of punctuationas shown below butsoftwhat light through yonder window breaksit is the eastand juliet is the sun arisefair sunand kill the envious moonwho is already sick and pale with griefsince the python split function looks for spaces and treats words as tokens separated by spaceswe would treat the words "soft!and "softas different words and create separate dictionary entry for each word also since the file has capitalizationwe would treat "whoand "whoas different words with different counts we can solve both these problems by using the string methods lowerpunctuationand translate the translate is the most subtle of the methods here is the documentation for translateline translate(str maketrans(fromstrtostrdeletestr)replace the characters in fromstr with the character in the same position in tostr and delete all characters that are in deletestr the fromstr and tostr can be empty strings and the deletestr parameter can be omitted we will not specify the tostr but we will use the deletestr parameter to delete all of the punctuation we will even let python tell us the list of characters that it considers "punctuation"import string string punctuation '!"#$%&\'()*+,/:;?@[\\]^ `{|}~the parameters used by translate were different in python we make the following modifications to our programimport string fname input('enter the file name'tryfhand open(fnameexceptprint('file cannot be opened:'fnameexit(counts dict(for line in fhandline line rstrip(
6,548
dictionaries line line translate(line maketrans(''''string punctuation)line line lower(words line split(for word in wordsif word not in countscounts[word elsecounts[word+ print(countscodepart of learning the "art of pythonor "thinking pythonicallyis realizing that python often has built-in capabilities for many common data analysis problems over timeyou will see enough example code and read enough of the documentation to know where to look to see if someone has already written something that makes your job much easier the following is an abbreviated version of the outputenter the file nameromeo-full txt {'swearst' 'all' 'afeard' 'leave' 'these' 'kinsmen' 'what' 'thinkst' 'love' 'cloak' ' 'orchard' 'light' 'lovers' 'romeo' 'maiden' 'whiteupturned' 'juliet' 'gentleman' 'it' 'leans' 'canst' 'having' looking through this output is still unwieldy and we can use python to give us exactly what we are looking forbut to do sowe need to learn about python tuples we will pick up this example once we learn about tuples debugging as you work with bigger datasets it can become unwieldy to debug by printing and checking data by hand here are some suggestions for debugging large datasetsscale down the input if possiblereduce the size of the dataset for example if the program reads text filestart with just the first linesor with the smallest example you can find you can either edit the files themselvesor (bettermodify the program so it reads only the first lines if there is an erroryou can reduce to the smallest value that manifests the errorand then increase it gradually as you find and correct errors check summaries and types instead of printing and checking the entire datasetconsider printing summaries of the datafor examplethe number of items in dictionary or the total of list of numbers common cause of runtime errors is value that is not the right type for debugging this kind of errorit is often enough to print the type of value
6,549
write self-checks sometimes you can write code to check for errors automatically for exampleif you are computing the average of list of numbersyou could check that the result is not greater than the largest element in the list or less than the smallest this is called "sanity checkbecause it detects results that are "completely illogicalanother kind of check compares the results of two different computations to see if they are consistent this is called "consistency checkpretty print the output formatting debugging output can make it easier to spot an error againtime you spend building scaffolding can reduce the time you spend debugging glossary dictionary mapping from set of keys to their corresponding values hashtable the algorithm used to implement python dictionaries hash function function used by hashtable to compute the location for key histogram set of counters implementation way of performing computation item another name for key-value pair key an object that appears in dictionary as the first part of key-value pair key-value pair the representation of the mapping from key to value lookup dictionary operation that takes key and finds the corresponding value nested loops when there are one or more loops "insideof another loop the inner loop runs to completion each time the outer loop runs once value an object that appears in dictionary as the second part of key-value pair this is more specific than our previous use of the word "value exercises exercise write program that categorizes each mail message by which day of the week the commit was done to do this look for lines that start with "from"then look for the third word and keep running count of each of the days of the week at the end of the program print out the contents of your dictionary (order does not mattersample linefrom stephen marquard@uct ac za sat jan sample executionpython dow py enter file namembox-short txt {'fri' 'thu' 'sat' : :
6,550
dictionaries exercise write program to read through mail logbuild histogram using dictionary to count how many messages have come from each email addressand print the dictionary enter file namembox-short txt {'gopal ramasammycook@gmail com' 'louis@media berkeley edu' 'cwen@iupui edu' 'antranig@caret cam ac uk' 'rjlowe@iupui edu' 'gsilver@umich edu' 'david horwitz@uct ac za' 'wagnermr@iupui edu' 'zqian@umich edu' 'stephen marquard@uct ac za' 'ray@media berkeley edu' exercise add code to the above program to figure out who has the most messages in the file after all the data has been read and the dictionary has been createdlook through the dictionary using maximum loop (see maximum and minimum loopsto find who has the most messages and print how many messages the person has enter file namembox-short txt cwen@iupui edu enter file namembox txt zqian@umich edu exercise this program records the domain name (instead of the addresswhere the message was sent from instead of who the mail came from ( the whole email addressat the end of the programprint out the contents of your dictionary python schoolcount py enter file namembox-short txt {'media berkeley edu' 'uct ac za' 'umich edu' 'gmail com' 'caret cam ac uk' 'iupui edu'
6,551
tuples tuples are immutable tuple is sequence of values much like list the values stored in tuple can be any typeand they are indexed by integers the important difference is that tuples are immutable tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in python dictionaries syntacticallya tuple is comma-separated list of valuest ' '' '' '' ''ealthough it is not necessaryit is common to enclose tuples in parentheses to help us quickly identify tuples when we look at python codet (' '' '' '' '' 'to create tuple with single elementyou have to include the final commat (' ',type( without the comma python treats (' 'as an expression with string in parentheses that evaluates to stringt (' 'type( another way to construct tuple is the built-in function tuple with no argumentit creates an empty tuple fun factthe word "tuplecomes from the names given to sequences of numbers of varying lengthssingledoubletriplequadruplequintuplesextupleseptupleetc
6,552
tuples tuple(print( (if the argument is sequence (stringlistor tuple)the result of the call to tuple is tuple with the elements of the sequencet tuple('lupins'print( (' '' '' '' '' '' 'because tuple is the name of constructoryou should avoid using it as variable name most list operators also work on tuples the bracket operator indexes an elementt (' '' '' '' '' 'print( [ ]'aand the slice operator selects range of elements print( [ : ](' '' 'but if you try to modify one of the elements of the tupleyou get an errort[ 'atypeerrorobject doesn' support item assignment you can' modify the elements of tuplebut you can replace one tuple with anothert (' ', [ :print( (' '' '' '' '' ' comparing tuples the comparison operators work with tuples and other sequences python starts by comparing the first element from each sequence if they are equalit goes on to the next elementand so onuntil it finds elements that differ subsequent elements are not considered (even if they are really big( ( true ( ( true
6,553
the sort function works the same way it sorts primarily by first elementbut in the case of tieit sorts by second elementand so on this feature lends itself to pattern called dsu for decorate sequence by building list of tuples with one or more sort keys preceding the elements from the sequencesort the list of tuples using the python built-in sortand undecorate by extracting the sorted elements of the sequence for examplesuppose you have list of words and you want to sort them from longest to shortesttxt 'but soft what light in yonder window breakswords txt split( list(for word in wordst append((len(word)word) sort(reverse=trueres list(for lengthword in tres append(wordprint(rescodethe first loop builds list of tupleswhere each tuple is word preceded by its length sort compares the first elementlengthfirstand only considers the second element to break ties the keyword argument reverse=true tells sort to go in decreasing order the second loop traverses the list of tuples and builds list of words in descending order of length the four-character words are sorted in reverse alphabetical orderso "whatappears before "softin the following list the output of the program is as follows['yonder''window''breaks''light''what''soft''but''in'of course the line loses much of its poetic impact when turned into python list and sorted in descending word length order
6,554
tuples tuple assignment one of the unique syntactic features of the python language is the ability to have tuple on the left side of an assignment statement this allows you to assign more than one variable at time when the left side is sequence in this example we have two-element list (which is sequenceand assign the first and second elements of the sequence to the variables and in single statement 'have''funxy 'havey 'funit is not magicpython roughly translates the tuple assignment syntax to be the following: 'have''funx [ [ 'havey 'funstylistically when we use tuple on the left side of the assignment statementwe omit the parenthesesbut the following is an equally valid syntaxm 'have''fun(xym 'havey 'funa particularly clever application of tuple assignment allows us to swap the values of two variables in single statementab ba python does not translate the syntax literally for exampleif you try this with dictionaryit will not work as you might expect
6,555
both sides of this statement are tuplesbut the left side is tuple of variablesthe right side is tuple of expressions each value on the right side is assigned to its respective variable on the left side all the expressions on the right side are evaluated before any of the assignments the number of variables on the left and the number of values on the right must be the sameab valueerrortoo many values to unpack more generallythe right side can be any kind of sequence (stringlistor tuplefor exampleto split an email address into user name and domainyou could writeaddr 'monty@python orgunamedomain addr split('@'the return value from split is list with two elementsthe first element is assigned to unamethe second to domain print(unamemonty print(domainpython org dictionaries and tuples dictionaries have method called items that returns list of tupleswhere each tuple is key-value paird {' ': ' ': ' ': list( items()print( [(' ' )(' ' )(' ' )as you should expect from dictionarythe items are in no particular order howeversince the list of tuples is listand tuples are comparablewe can now sort the list of tuples converting dictionary to list of tuples is way for us to output the contents of dictionary sorted by keyd {' ': ' ': ' ': list( items() [(' ' )(' ' )(' ' ) sort( [(' ' )(' ' )(' ' )the new list is sorted in ascending alphabetical order by the key value
6,556
tuples multiple assignment with dictionaries combining itemstuple assignmentand foryou can see nice code pattern for traversing the keys and values of dictionary in single loopfor keyval in list( items())print(valkeythis loop has two iteration variables because items returns list of tuples and keyval is tuple assignment that successively iterates through each of the key-value pairs in the dictionary for each iteration through the loopboth key and value are advanced to the next key-value pair in the dictionary (still in hash orderthe output of this loop is againit is in hash key order ( no particular orderif we combine these two techniqueswe can print out the contents of dictionary sorted by the value stored in each key-value pair to do thiswe first make list of tuples where each tuple is (valuekeythe items method would give us list of (keyvaluetuplesbut this time we want to sort by valuenot key once we have constructed the list with the value-key tuplesit is simple matter to sort the list in reverse order and print out the newsorted list {' ': ' ': ' ': list(for keyval in items( append(valkeyl [( ' ')( ' ')( ' ') sort(reverse=truel [( ' ')( ' ')( ' ')by carefully constructing the list of tuples to have the value as the first element of each tuplewe can sort the list of tuples and get our dictionary contents sorted by value
6,557
the most common words coming back to our running example of the text from romeo and juliet act scene we can augment our program to use this technique to print the ten most common words in the text as followsimport string fhand open('romeo-full txt'counts dict(for line in fhandline line translate(str maketrans(''''string punctuation)line line lower(words line split(for word in wordsif word not in countscounts[word elsecounts[word+ sort the dictionary by value lst list(for keyval in list(counts items())lst append((valkey)lst sort(reverse=truefor keyval in lst[: ]print(keyvalcodethe first part of the program which reads the file and computes the dictionary that maps each word to the count of words in the document is unchanged but instead of simply printing out counts and ending the programwe construct list of (valkeytuples and then sort the list in reverse order since the value is firstit will be used for the comparisons if there is more than one tuple with the same valueit will look at the second element (the key)so tuples where the value is the same will be further sorted by the alphabetical order of the key at the end we write nice for loop which does multiple assignment iteration and prints out the ten most common words by iterating through slice of the list (lst[: ]so now the output finally looks like what we want for our word frequency analysis and romeo to the
6,558
tuples thou juliet that my thee the fact that this complex data parsing and analysis can be done with an easy-tounderstand -line python program is one reason why python is good choice as language for exploring information using tuples as keys in dictionaries because tuples are hashable and lists are notif we want to create composite key to use in dictionary we must use tuple as the key we would encounter composite key if we wanted to create telephone directory that maps from last-namefirst-name pairs to telephone numbers assuming that we have defined the variables lastfirstand numberwe could write dictionary assignment statement as followsdirectory[last,firstnumber the expression in brackets is tuple we could use tuple assignment in for loop to traverse this dictionary for lastfirst in directoryprint(firstlastdirectory[last,first]this loop traverses the keys in directorywhich are tuples it assigns the elements of each tuple to last and firstthen prints the name and corresponding telephone number sequencesstringslistsand tuples oh myi have focused on lists of tuplesbut almost all of the examples in this also work with lists of liststuples of tuplesand tuples of lists to avoid enumerating the possible combinationsit is sometimes easier to talk about sequences of sequences in many contextsthe different kinds of sequences (stringslistsand tuplescan be used interchangeably so how and why do you choose one over the othersto start with the obviousstrings are more limited than other sequences because the elements have to be characters they are also immutable if you need the ability to change the characters in string (as opposed to creating new string)you might want to use list of characters instead lists are more common than tuplesmostly because they are mutable but there are few cases where you might prefer tuples
6,559
in some contextslike return statementit is syntactically simpler to create tuple than list in other contextsyou might prefer list if you want to use sequence as dictionary keyyou have to use an immutable type like tuple or string if you are passing sequence as an argument to functionusing tuples reduces the potential for unexpected behavior due to aliasing because tuples are immutablethey don' provide methods like sort and reversewhich modify existing lists however python provides the built-in functions sorted and reversedwhich take any sequence as parameter and return new sequence with the same elements in different order list comprehension sometimes you want to create sequence by using data from another sequence you can achieve this by writing for loop and appending one item at time for exampleif you wanted to convert list of strings each string storing digits into numbers that you can sum upyou would writelist_of_ints_in_strings [' '' '' 'list_of_ints [for in list_of_ints_in_stringslist_of_ints append(int( )print(sum(list_of_ints)with list comprehensionthe above code can be written in more compact mannerlist_of_ints_in_strings [' '' '' 'list_of_ints int(xfor in list_of_ints_in_strings print(sum(list_of_ints) debugging listsdictionaries and tuples are known generically as data structuresin this we are starting to see compound data structureslike lists of tuplesand dictionaries that contain tuples as keys and lists as values compound data structures are usefulbut they are prone to what call shape errorsthat iserrors caused when data structure has the wrong typesizeor compositionor perhaps you write some code and forget the shape of your data and introduce an error for exampleif you are expecting list with one integer and give you plain old integer (not in list)it won' work
6,560
tuples glossary comparable type where one value can be checked to see if it is greater thanless thanor equal to another value of the same type types which are comparable can be put in list and sorted data structure collection of related valuesoften organized in listsdictionariestuplesetc dsu abbreviation of "decorate-sort-undecorate" pattern that involves building list of tuplessortingand extracting part of the result gather the operation of assembling variable-length argument tuple hashable type that has hash function immutable types like integersfloatsand strings are hashablemutable types like lists and dictionaries are not scatter the operation of treating sequence as list of arguments shape (of data structurea summary of the typesizeand composition of data structure singleton list (or other sequencewith single element tuple an immutable sequence of elements tuple assignment an assignment with sequence on the right side and tuple of variables on the left the right side is evaluated and then its elements are assigned to the variables on the left exercises exercise revise previous program as followsread and parse the "fromlines and pull out the addresses from the line count the number of messages from each person using dictionary after all the data has been readprint the person with the most commits by creating list of (countemailtuples from the dictionary then sort the list in reverse order and print out the person who has the most commits sample linefrom stephen marquard@uct ac za sat jan : : enter file namembox-short txt cwen@iupui edu enter file namembox txt zqian@umich edu exercise this program counts the distribution of the hour of the day for each of the messages you can pull the hour from the "fromline by finding the time string and then splitting that string into parts using the colon character once you have accumulated the counts for each hourprint out the countsone per linesorted by hour as shown below python timeofday py enter file namembox-short txt
6,561
exercise write program that reads file and prints the letters in decreasing order of frequency your program should convert all the input to lower case and only count the letters - your program should not count spacesdigitspunctuationor anything other than the letters - find text samples from several different languages and see how letter frequency varies between languages compare your results with the tables at
6,562
tuples
6,563
regular expressions so far we have been reading through fileslooking for patterns and extracting various bits of lines that we find interesting we have been using string methods like split and find and using lists and string slicing to extract portions of the lines this task of searching and extracting is so common that python has very powerful library called regular expressions that handles many of these tasks quite elegantly the reason we have not introduced regular expressions earlier in the book is because while they are very powerfulthey are little complicated and their syntax takes some getting used to regular expressions are almost their own little programming language for searching and parsing strings as matter of factentire books have been written on the topic of regular expressions in this we will only cover the basics of regular expressions for more detail on regular expressionsseethe regular expression library re must be imported into your program before you can use it the simplest use of the regular expression library is the search(function the following program demonstrates trivial use of the search function search for lines that contain 'fromimport re hand open('mbox-short txt'for line in handline line rstrip(if re search('from:'line)print(linecodewe open the fileloop through each lineand use the regular expression search(to only print out lines that contain the string "from:this program does not
6,564
regular expressions use the real power of regular expressionssince we could have just as easily used line find(to accomplish the same result the power of the regular expressions comes when we add special characters to the search string that allow us to more precisely control which lines match the string adding these special characters to our regular expression allow us to do sophisticated matching and extraction while writing very little code for examplethe caret character is used in regular expressions to match "the beginningof line we could change our program to only match lines where "from:was at the beginning of the line as followssearch for lines that start with 'fromimport re hand open('mbox-short txt'for line in handline line rstrip(if re search('^from:'line)print(linecodenow we will only match lines that start with the string "from:this is still very simple example that we could have done equivalently with the startswith(method from the string library but it serves to introduce the notion that regular expressions contain special action characters that give us more control as to what will match the regular expression character matching in regular expressions there are number of other special characters that let us build even more powerful regular expressions the most commonly used special character is the period or full stopwhich matches any character in the following examplethe regular expression mwould match any of the strings "from:""fxxm:"" :"or " !@ :since the period characters in the regular expression match any character search for lines that start with ' 'followed by charactersfollowed by ' :import re hand open('mbox-short txt'for line in handline line rstrip(if re search('^ :'line)print(linecode
6,565
this is particularly powerful when combined with the ability to indicate that character can be repeated any number of times using the or characters in your regular expression these special characters mean that instead of matching single character in the search stringthey match zero-or-more characters (in the case of the asteriskor one-or-more of the characters (in the case of the plus signwe can further narrow down the lines that we match using repeated wild card character in the following examplesearch for lines that start with from and have an at sign import re hand open('mbox-short txt'for line in handline line rstrip(if re search('^from+@'line)print(linecodethe search string ^from+will successfully match lines that start with "from:"followed by one or more characters +)followed by an at-sign so this will match the following linefromstephen marquard@uct ac za you can think of the wildcard as expanding to match all the characters between the colon character and the at-sign from+it is good to think of the plus and asterisk characters as "pushyfor examplethe following string would match the last at-sign in the string as the pushes outwardsas shown belowfromstephen marquard@uct ac zacsev@umich eduand cwen @iupui edu it is possible to tell an asterisk or plus sign not to be so "greedyby adding another character see the detailed documentation for information on turning off the greedy behavior extracting data using regular expressions if we want to extract data from string in python we can use the findall(method to extract all of the substrings which match regular expression let' use the example of wanting to extract anything that looks like an email address from any line regardless of format for examplewe want to pull the email addresses from each of the following lines
6,566
regular expressions from stephen marquard@uct ac za sat jan : : return-pathfor received(from apache@localhostauthorstephen marquard@uct ac za we don' want to write code for each of the types of linessplitting and slicing differently for each line this following program uses findall(to find the lines with email addresses in them and extract one or more addresses from each of those lines import re ' message from csev@umich edu to cwen@iupui edu about meeting @ pmlst re findall('\ +@\ +'sprint(lstcodethe findall(method searches the string in the second argument and returns list of all of the strings that look like email addresses we are using two-character sequence that matches non-whitespace character (\sthe output of the program would be['csev@umich edu''cwen@iupui edu'translating the regular expressionwe are looking for substrings that have at least one non-whitespace characterfollowed by an at-signfollowed by at least one more non-whitespace character the \smatches as many non-whitespace characters as possible the regular expression would match twice (csev@umich edu and cwen@iupui edu)but it would not match the string "@ pmbecause there are no non-blank characters before the at-sign we can use this regular expression in program to read all the lines in file and print out anything that looks like an email address as followssearch for lines that have an at sign between characters import re hand open('mbox-short txt'for line in handline line rstrip( re findall('\ +@\ +'lineif len( print(xcodewe read each line and then extract all the substrings that match our regular expression since findall(returns listwe simply check if the number of
6,567
elements in our returned list is more than zero to print only lines where we found at least one substring that looks like an email address if we run the program on mbox-short txt we get the following output[';'[';'['apache@localhost)'['source@collab sakaiproject org;'['cwen@iupui edu'['source@collab sakaiproject org'['cwen@iupui edu'['cwen@iupui edu'['wagnermr@iupui edu'some of our email addresses have incorrect characters like "<or ";at the beginning or end let' declare that we are only interested in the portion of the string that starts and ends with letter or number to do thiswe use another feature of regular expressions square brackets are used to indicate set of multiple acceptable characters we are willing to consider matching in sensethe \ is asking to match the set of "non-whitespace charactersnow we will be little more explicit in terms of the characters we will match here is our new regular expression[ -za- - ]\ *@\ *[ -za-zthis is getting little complicated and you can begin to see why regular expressions are their own little language unto themselves translating this regular expressionwe are looking for substrings that start with single lowercase letteruppercase letteror number "[ -za- - ]"followed by zero or more non-blank characters (\ *)followed by an at-signfollowed by zero or more non-blank characters (\ *)followed by an uppercase or lowercase letter note that we switched from to to indicate zero or more non-blank characters since [ -za- - is already one non-blank character remember that the or applies to the single character immediately to the left of the plus or asterisk if we use this expression in our programour data is much cleanersearch for lines that have an at sign between characters the characters must be letter or number import re hand open('mbox-short txt'for line in handline line rstrip( re findall('[ -za- - ]\ *@\ *[ -za- ]'lineif len( print(xcode
6,568
regular expressions ['wagnermr@iupui edu'['cwen@iupui edu'['postmaster@collab sakaiproject org'[' lmfo @nakamura uits iupui edu'['source@collab sakaiproject org'['source@collab sakaiproject org'['source@collab sakaiproject org'['apache@localhost'notice that on the source@collab sakaiproject org linesour regular expression eliminated two letters at the end of the string (">;"this is because when we append [ -za-zto the end of our regular expressionwe are demanding that whatever string the regular expression parser finds must end with letter so when it sees the ">at the end of "sakaiproject org>;it simply stops at the last "matchingletter it found ( the "gwas the last good matchalso note that the output of the program is python list that has string as the single element in the list combining searching and extracting if we want to find numbers on lines that start with the string " -such asx-dspam-confidence -dspam-probability we don' just want any floating-point numbers from any lines we only want to extract numbers from lines that have the above syntax we can construct the following regular expression to select the lines^ *[ - ]translating thiswe are sayingwe want lines that start with -followed by zero or more characters *)followed by colon (:and then space after the space we are looking for one or more characters that are either digit ( - or period [ - ]note that inside the square bracketsthe period matches an actual period ( it is not wildcard between the square bracketsthis is very tight expression that will pretty much match only the lines we are interested in as followssearch for lines that start with 'xfollowed by any non whitespace characters and ':followed by space and any number the number can include decimal import re hand open('mbox-short txt'for line in hand
6,569
line line rstrip(if re search('^ \ *[ - ]+'line)print(linecodewhen we run the programwe see the data nicely filtered to show only the lines we are looking for -dspam-confidence -dspam-probability -dspam-confidence -dspam-probability but now we have to solve the problem of extracting the numbers while it would be simple enough to use splitwe can use another feature of regular expressions to both search and parse the line at the same time parentheses are another special character in regular expressions when you add parentheses to regular expressionthey are ignored when matching the string but when you are using findall()parentheses indicate that while you want the whole expression to matchyou only are interested in extracting portion of the substring that matches the regular expression so we make the following change to our programsearch for lines that start with 'xfollowed by any non whitespace characters and ':followed by space and any number the number can include decimal then print the number if it is greater than zero import re hand open('mbox-short txt'for line in handline line rstrip( re findall('^ \ *([ - ]+)'lineif len( print(xcodeinstead of calling search()we add parentheses around the part of the regular expression that represents the floating-point number to indicate we only want findall(to give us back the floating-point number portion of the matching string the output from this program is as follows[' '[' '[' '
6,570
regular expressions [' '[' '[' 'the numbers are still in list and need to be converted from strings to floating pointbut we have used the power of regular expressions to both search and extract the information we found interesting as another example of this techniqueif you look at the file there are number of lines of the formdetailsif we wanted to extract all of the revision numbers (the integer number at the end of these linesusing the same technique as abovewe could write the following programsearch for lines that start with 'detailsrev=followed by numbers then print the number if one is found import re hand open('mbox-short txt'for line in handline line rstrip( re findall('^details*rev=([ - ]+)'lineif len( print(xcodetranslating our regular expressionwe are looking for lines that start with details:followed by any number of characters *)followed by rev=and then by one or more digits we want to find lines that match the entire expression but we only want to extract the integer number at the end of the lineso we surround [ - ]with parentheses when we run the programwe get the following output[' '[' '[' '[' 'remember that the [ - ]is "greedyand it tries to make as large string of digits as possible before extracting those digits this "greedybehavior is why we get all five digits for each number the regular expression library expands in both directions until it encounters non-digitor the beginning or the end of line now we can use regular expressions to redo an exercise from earlier in the book where we were interested in the time of day of each mail message we looked for lines of the form
6,571
from stephen marquard@uct ac za sat jan : : and wanted to extract the hour of the day for each line previously we did this with two calls to split first the line was split into words and then we pulled out the fifth word and split it again on the colon character to pull out the two characters we were interested in while this workedit actually results in pretty brittle code that is assuming the lines are nicely formatted if you were to add enough error checking (or big try/except blockto insure that your program never failed when presented with incorrectly formatted linesthe code would balloon to - lines of code that was pretty hard to read we can do this in far simpler way with the following regular expression^from [ - ][ - ]the translation of this regular expression is that we are looking for lines that start with from (note the space)followed by any number of characters *)followed by spacefollowed by two digits [ - ][ - ]followed by colon character this is the definition of the kinds of lines we are looking for in order to pull out only the hour using findall()we add parentheses around the two digits as follows^from ([ - ][ - ])this results in the following programsearch for lines that start with from and character followed by two digit number between and followed by ':then print the number if it is greater than zero import re hand open('mbox-short txt'for line in handline line rstrip( re findall('^from ([ - ][ - ]):'lineif len( print(xcodewhen the program runsit produces the following output[' '[' '[' '[' '
6,572
regular expressions escape character since we use special characters in regular expressions to match the beginning or end of line or specify wild cardswe need way to indicate that these characters are "normaland we want to match the actual character such as dollar sign or caret we can indicate that we want to simply match character by prefixing that character with backslash for examplewe can find money amounts with the following regular expression import re 'we just received $ for cookies re findall('\$[ - ]+',xsince we prefix the dollar sign with backslashit actually matches the dollar sign in the input string instead of matching the "end of line"and the rest of the regular expression matches one or more digits or the period character noteinside square bracketscharacters are not "specialso when we say [ - ]it really means digits or period outside of square bracketsa period is the "wildcardcharacter and matches any character inside square bracketsthe period is period summary while this only scratched the surface of regular expressionswe have learned bit about the language of regular expressions they are search strings with special characters in them that communicate your wishes to the regular expression system as to what defines "matchingand what is extracted from the matched strings here are some of those special characters and character sequencesmatches the beginning of the line matches the end of the line matches any character ( wildcard\ matches whitespace character \ matches non-whitespace character (opposite of \sapplies to the immediately preceding character(sand indicates to match zero or more times *applies to the immediately preceding character(sand indicates to match zero or more times in "non-greedy modeapplies to the immediately preceding character(sand indicates to match one or more times +applies to the immediately preceding character(sand indicates to match one or more times in "non-greedy mode
6,573
applies to the immediately preceding character(sand indicates to match zero or one time ?applies to the immediately preceding character(sand indicates to match zero or one time in "non-greedy mode[aeioumatches single character as long as that character is in the specified set in this exampleit would match " "" "" "" "or " "but no other characters [ - - you can specify ranges of characters using the minus sign this example is single character that must be lowercase letter or digit [^ -za-zwhen the first character in the set notation is caretit inverts the logic this example matches single character that is anything other than an uppercase or lowercase letter when parentheses are added to regular expressionthey are ignored for the purpose of matchingbut allow you to extract particular subset of the matched string rather than the whole string when using findall(\ matches the empty stringbut only at the start or end of word \ matches the empty stringbut not at the start or end of word \ matches any decimal digitequivalent to the set [ - \ matches any non-digit characterequivalent to the set [^ - bonus section for unix linux users support for searching files using regular expressions was built into the unix operating system since the and it is available in nearly all programming languages in one form or another as matter of factthere is command-line program built into unix called grep (generalized regular expression parserthat does pretty much the same as the search(examples in this so if you have macintosh or linux systemyou can try the following commands in your command-line window grep '^from:mbox-short txt fromstephen marquard@uct ac za fromlouis@media berkeley edu fromzqian@umich edu fromrjlowe@iupui edu this tells grep to show you lines that start with the string "from:in the file mbox-short txt if you experiment with the grep command bit and read the documentation for grepyou will find some subtle differences between the regular expression support in python and the regular expression support in grep as an examplegrep does not support the non-blank character \ so you will need to use the slightly more complex set notation []which simply means match character that is anything other than space
6,574
regular expressions debugging python has some simple and rudimentary built-in documentation that can be quite helpful if you need quick refresher to trigger your memory about the exact name of particular method this documentation can be viewed in the python interpreter in interactive mode you can bring up an interactive help system using help(help(helpmodules if you know what module you want to useyou can use the dir(command to find the methods in the module as followsimport re dir(re'compile''copy_reg''error''escape''findall''finditer'match''purge''search''split''sre_compile''sre_parse'sub''subn''sys''template'you can also get small amount of documentation on particular method using the dir command help (re searchhelp on function search in module research(patternstringflags= scan through string looking for match to the patternreturning match objector none if no match was found the built-in documentation is not very extensivebut it can be helpful when you are in hurry or don' have access to web browser or search engine glossary brittle code code that works when the input data is in particular format but is prone to breakage if there is some deviation from the correct format we call this "brittle codebecause it is easily broken greedy matching the notion that the and characters in regular expression expand outward to match the largest possible string grep command available in most unix systems that searches through text files looking for lines that match regular expressions the command name stands for "generalized regular expression parser
6,575
regular expression language for expressing more complex search strings regular expression may contain special characters that indicate that search only matches at the beginning or end of line or many other similar capabilities wild card special character that matches any character in regular expressions the wild-card character is the period exercises exercise write simple program to simulate the operation of the grep command on unix ask the user to enter regular expression and count the number of lines that matched the regular expressionpython grep py enter regular expression^author mbox txt had lines that matched ^author python grep py enter regular expression^xmbox txt had lines that matched ^xpython grep py enter regular expressionjavambox txt had lines that matched javaexercise write program to look for lines of the formnew revision extract the number from each of the lines using regular expression and the findall(method compute the average of the numbers and print out the average as an integer enter file:mbox txt enter file:mbox-short txt
6,576
regular expressions
6,577
networked programs while many of the examples in this book have focused on reading files and looking for data in those filesthere are many different sources of information when one considers the internet in this we will pretend to be web browser and retrieve web pages using the hypertext transfer protocol (httpthen we will read through the web page data and parse it hypertext transfer protocol http the network protocol that powers the web is actually quite simple and there is built-in support in python called socket which makes it very easy to make network connections and retrieve data over those sockets in python program socket is much like fileexcept that single socket provides two-way connection between two programs you can both read from and write to the same socket if you write something to socketit is sent to the application at the other end of the socket if you read from the socketyou are given the data which the other application has sent but if you try to read socket when the program on the other end of the socket has not sent any datayou just sit and wait if the programs on both ends of the socket simply wait for some data without sending anythingthey will wait for very long timeso an important part of programs that communicate over the internet is to have some sort of protocol protocol is set of precise rules that determine who is to go firstwhat they are to doand then what the responses are to that messageand who sends nextand so on in sense the two applications at either end of the socket are doing dance and making sure not to step on each other' toes there are many documents that describe these network protocols the hypertext transfer protocol is described in the following document
6,578
networked programs this is long and complex -page document with lot of detail if you find it interestingfeel free to read it all but if you take look around page of rfc you will find the syntax for the get request to request document from web serverwe make connection to the www pr org server on port and then send line of the form get where the second parameter is the web page we are requestingand then we also send blank line the web server will respond with some header information about the document and blank line followed by the document content the world' simplest web browser perhaps the easiest way to show how the http protocol works is to write very simple python program that makes connection to web server and follows the rules of the http protocol to request document and display what the server sends back import socket mysock socket socket(socket af_inetsocket sock_streammysock connect(('data pr org' )cmd 'get mysock send(cmdwhile truedata mysock recv( if len(data break print(data decode(),end=''mysock close(codefirst the program makes connection to port on the server www py com since our program is playing the role of the "web browser"the http protocol says we must send the get command followed by blank line \ \ signifies an eol (end of line)so \ \ \ \ signifies nothing between two eol sequences that is the equivalent of blank line once we send that blank linewe write loop that receives data in -character chunks from the socket and prints the data out until there is no more data to read ( the recv(returns an empty stringthe program produces the following outputhttp/ ok datewed apr : : gmt serverapache(ubuntu
6,579
your program www py com socket connect send recv port web pages figure socket connection last-modifiedsat may : : gmt etag" - accept-rangesbytes content-length cache-controlmax-age= no-cacheno-storemust-revalidate pragmano-cache expireswed jan : : gmt connectionclose content-typetext/plain but soft what light through yonder window breaks it is the east and juliet is the sun arise fair sun and kill the envious moon who is already sick and pale with grief the output starts with headers which the web server sends to describe the document for examplethe content-type header indicates that the document is plain text document (text/plainafter the server sends us the headersit adds blank line to indicate the end of the headersand then sends the actual data of the file romeo txt this example shows how to make low-level network connection with sockets sockets can be used to communicate with web server or with mail server or many other kinds of servers all that is needed is to find the document which describes the protocol and write the code to send and receive the data according to the protocol howeversince the protocol that we use most commonly is the http web protocolpython has special library specifically designed to support the http protocol for the retrieval of documents and data over the web one of the requirements for using the http protocol is the need to send and receive data as bytes objectsinstead of strings in the preceding examplethe encode(and decode(methods convert strings into bytes objects and back again the next example uses 'notation to specify that variable should be stored as bytes object encode(and 'are equivalent
6,580
networked programs 'hello worldb'hello world'hello worldencode( 'hello world retrieving an image over http in the above examplewe retrieved plain text file which had newlines in the file and we simply copied the data to the screen as the program ran we can use similar program to retrieve an image across using http instead of copying the data to the screen as the program runswe accumulate the data in stringtrim off the headersand then save the image data to file as followsimport socket import time host 'data pr orgport mysock socket socket(socket af_inetsocket sock_streammysock connect((hostport)mysock sendall( 'get count picture "while truedata mysock recv( if len(data break #time sleep( count count len(dataprint(len(data)countpicture picture data mysock close(look for the end of the header ( crlfpos picture find( "\ \ \ \ "print('header length'posprint(picture[:posdecode()skip past the header and save the picture data picture picture[pos+ :fhand open("stuff jpg""wb"fhand write(picturefhand close(codewhen the program runsit produces the following output
6,581
python urljpeg py header length http/ ok datewed apr : : gmt serverapache(ubuntulast-modifiedmon may : : gmt etag" - accept-rangesbytes content-length varyaccept-encoding cache-controlmax-age= no-cacheno-storemust-revalidate pragmano-cache expireswed jan : : gmt connectionclose content-typeimage/jpeg you can see that for this urlthe content-type header indicates that body of the document is an image (image/jpegonce the program completesyou can view the image data by opening the file stuff jpg in an image viewer as the program runsyou can see that we don' get characters each time we call the recv(method we get as many characters as have been transferred across the network to us by the web server at the moment we call recv(in this examplewe either get as few as characters each time we request up to characters of data your results may be different depending on your network speed also note that on the last call to recv(we get byteswhich is the end of the streamand in the next call to recv(we get zero-length string that tells us that the server has called close(on its end of the socket and there is no more data forthcoming we can slow down our successive recv(calls by uncommenting the call to time sleep(this waywe wait quarter of second after each call so that the server can "get aheadof us and send more data to us before we call recv(again with the delayin place the program executes as followspython urljpeg py header length
6,582
networked programs http/ ok datewed apr : : gmt serverapache(ubuntulast-modifiedmon may : : gmt etag" - accept-rangesbytes content-length varyaccept-encoding cache-controlmax-age= no-cacheno-storemust-revalidate pragmano-cache expireswed jan : : gmt connectionclose content-typeimage/jpeg now other than the first and last calls to recv()we now get characters each time we ask for new data there is buffer between the server making send(requests and our application making recv(requests when we run the program with the delay in placeat some point the server might fill up the buffer in the socket and be forced to pause until our program starts to empty the buffer the pausing of either the sending application or the receiving application is called "flow control retrieving web pages with urllib while we can manually send and receive data over http using the socket librarythere is much simpler way to perform this common task in python by using the urllib library using urllibyou can treat web page much like file you simply indicate which web page you would like to retrieve and urllib handles all of the http protocol and header details the equivalent code to read the romeo txt file from the web using urllib is as followsimport urllib request fhand urllib request urlopen('for line in fhandprint(line decode(strip()codeonce the web page has been opened with urllib urlopenwe can treat it like file and read through it using for loop when the program runswe only see the output of the contents of the file the headers are still sentbut the urllib code consumes the headers and only returns the data to us
6,583
but soft what light through yonder window breaks it is the east and juliet is the sun arise fair sun and kill the envious moon who is already sick and pale with grief as an examplewe can write program to retrieve the data for romeo txt and compute the frequency of each word in the file as followsimport urllib requesturllib parseurllib error fhand urllib request urlopen('counts dict(for line in fhandwords line decode(split(for word in wordscounts[wordcounts get(word print(countscodeagainonce we have opened the web pagewe can read it like local file reading binary files using urllib sometimes you want to retrieve non-text (or binaryfile such as an image or video file the data in these files is generally not useful to print outbut you can easily make copy of url to local file on your hard disk using urllib the pattern is to open the url and use read to download the entire contents of the document into string variable (imgthen write that information to local file as followsimport urllib requesturllib parseurllib error img urllib request urlopen('fhand open('cover jpg''wb'fhand write(imgfhand close(codethis program reads all of the data in at once across the network and stores it in the variable img in the main memory of your computerthen opens the file cover jpg and writes the data out to your disk the wb argument for open(opens binary file for writing only this program will work if the size of the file is less than the size of the memory of your computer however if this is large audio or video filethis program may crash or at least run extremely slowly when your computer runs out of memory in order to avoid
6,584
networked programs running out of memorywe retrieve the data in blocks (or buffersand then write each block to your disk before retrieving the next block this way the program can read any size file without using up all of the memory you have in your computer import urllib requesturllib parseurllib error img urllib request urlopen('fhand open('cover jpg''wb'size while trueinfo img read( if len(info break size size len(infofhand write(infoprint(size'characters copied 'fhand close(codein this examplewe read only , characters at time and then write those characters to the cover jpg file before retrieving the next , characters of data from the web this program runs as followspython curl py characters copied parsing html and scraping the web one of the common uses of the urllib capability in python is to scrape the web web scraping is when we write program that pretends to be web browser and retrieves pagesthen examines the data in those pages looking for patterns as an examplea search engine such as google will look at the source of one web page and extract the links to other pages and retrieve those pagesextracting linksand so on using this techniquegoogle spiders its way through nearly all of the pages on the web google also uses the frequency of links from pages it finds to particular page as one measure of how "importanta page is and how high the page should appear in its search results parsing html using regular expressions one simple way to parse html is to use regular expressions to repeatedly search for and extract substrings that match particular pattern here is simple web page
6,585
the first page if you likeyou can switch to the we can construct well-formed regular expression to match and extract the link values from the above text as followshref="http[ ]?:/+?our regular expression looks for strings that start with "href=""href="double quote the question mark behind the [ ]indicates to search for the string "httpfollowed by zero or one "sthe question mark added to the +indicates that the match is to be done in "non-greedyfashion instead of "greedyfashion non-greedy match tries to find the smallest possible matching string and greedy match tries to find the largest possible matching string we add parentheses to our regular expression to indicate which part of our matched string we would like to extractand produce the following programsearch for link values within url input import urllib requesturllib parseurllib error import re import ssl ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none url input('enter 'html urllib request urlopen(urlcontext=ctxread(links re findall( 'href="(http[ ]?:/*?)"'htmlfor link in linksprint(link decode()codethe ssl library allows this program to access web sites that strictly enforce https the read method returns html source code as bytes object instead of returning an httpresponse object the findall regular expression method will give us list of all of the strings that match our regular expressionreturning only the link text between the double quotes when we run the program and input urlwe get the following output
6,586
networked programs enter regular expressions work very nicely when your html is well formatted and predictable but since there are lot of "brokenhtml pages out therea solution only using regular expressions might either miss some valid links or end up with bad data this can be solved by using robust html parsing library parsing html using beautifulsoup even though html looks like xml and some pages are carefully constructed to be xmlmost html is generally broken in ways that cause an xml parser to reject the entire page of html as improperly formed there are number of python libraries which can help you parse html and extract data from the pages each of the libraries has its strengths and weaknesses and you can pick one based on your needs as an examplewe will simply parse some html input and extract links using the beautifulsoup library beautifulsoup tolerates highly flawed html and still lets you easily extract the data you need you can download and install the beautifulsoup code frominformation on installing beautifulsoup with the python package index tool pip is available atwe will use urllib to read the page and then use beautifulsoup to extract the href attributes from the anchor (atags to run thisdownload the beautifulsoup zip file and unzip it in the same directory as this file the xml format is described in the next
6,587
import urllib requesturllib parseurllib error from bs import beautifulsoup import ssl ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none url input('enter 'html urllib request urlopen(urlcontext=ctxread(soup beautifulsoup(html'html parser'retrieve all of the anchor tags tags soup(' 'for tag in tagsprint(tag get('href'none)codethe program prompts for web addressthen opens the web pagereads the data and passes the data to the beautifulsoup parserand then retrieves all of the anchor tags and prints out the href attribute for each tag when the program runsit produces the following outputenter genindex html py-modindex html whatsnew/ html whatsnew/index html tutorial/index html library/index html reference/index html using/index html howto/index html installing/index html distributing/index html extending/index html -api/index html faq/index html py-modindex html genindex html glossary html search html contents html bugs html about html license html copyright html download html
6,588
networked programs genindex html py-modindex html copyright html bugs html this list is much longer because some html anchor tags are relative paths ( tutorial/index htmlor in-page references ( '#'that do not include "or "you can use also beautifulsoup to pull out various parts of each tagto run thisdownload the beautifulsoup zip file and unzip it in the same directory as this file from urllib request import urlopen from bs import beautifulsoup import ssl ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none url input('enter 'html urlopen(urlcontext=ctxread(soup beautifulsoup(html"html parser"retrieve all of the anchor tags tags soup(' 'for tag in tagslook at the parts of tag print('tag:'tagprint('url:'tag get('href'none)print('contents:'tag contents[ ]print('attrs:'tag attrscodepython urllink py
6,589
enter tagurlcontent['\nsecond page'attrs[('href''html parser is the html parser included in the standard python library information on other html parsers is available atthese examples only begin to show the power of beautifulsoup when it comes to parsing html bonus section for unix linux users if you have linuxunixor macintosh computeryou probably have commands built in to your operating system that retrieves both plain text and binary files using the http or file transfer (ftpprotocols one of these commands is curlcurl - the command curl is short for "copy urland so the two examples listed earlier to retrieve binary files with urllib are cleverly named curl py and curl py on www py com/code as they implement similar functionality to the curl command there is also curl py sample program that does this task little more effectivelyin case you actually want to use this pattern in program you are writing second command that functions very similarly is wgetwget both of these commands make retrieving webpages and remote files simple task glossary beautifulsoup python library for parsing html documents and extracting data from html documents that compensates for most of the imperfections in the html that browsers generally ignore you can download the beautifulsoup code from www crummy com port number that generally indicates which application you are contacting when you make socket connection to server as an exampleweb traffic usually uses port while email traffic uses port
6,590
networked programs scrape when program pretends to be web browser and retrieves web pagethen looks at the web page content often programs are following the links in one page to find the next page so they can traverse network of pages or social network socket network connection between two applications where the applications can send and receive data in either direction spider the act of web search engine retrieving page and then all the pages linked from page and so on until they have nearly all of the pages on the internet which they use to build their search index exercises exercise change the socket program socket py to prompt the user for the url so it can read any web page you can use split('/'to break the url into its component parts so you can extract the host name for the socket connect call add error checking using try and except to handle the condition where the user enters an improperly formatted or non-existent url exercise change your socket program so that it counts the number of characters it has received and stops displaying any text after it has shown characters the program should retrieve the entire document and count the total number of characters and display the count of the number of characters at the end of the document exercise use urllib to replicate the previous exercise of ( retrieving the document from url( displaying up to charactersand ( counting the overall number of characters in the document don' worry about the headers for this exercisesimply show the first characters of the document contents exercise change the urllinks py program to extract and count paragraph (ptags from the retrieved html document and display the count of the paragraphs as the output of your program do not display the paragraph textonly count them test your program on several small web pages as well as some larger web pages exercise (advancedchange the socket program so that it only shows data after the headers and blank line have been received remember that recv receives characters (newlines and all)not lines
6,591
using web services once it became easy to retrieve documents and parse documents over http using programsit did not take long to develop an approach where we started producing documents that were specifically designed to be consumed by other programs ( not html to be displayed in browserthere are two common formats that we use when exchanging data across the web extensible markup language (xmlhas been in use for very long time and is best suited for exchanging document-style data when programs just want to exchange dictionarieslistsor other internal information with each otherthey use javascript object notation (json(see www json orgwe will look at both formats extensible markup language xml xml looks very similar to htmlbut xml is more structured than html here is sample of an xml documentchuck + each pair of opening ( and closing tags ( represents element or node with the same name as the tag ( personeach element can have some textsome attributes ( hide)and other nested elements if an xml element is empty ( has no content)then it may be depicted by self-closing tag ( often it is helpful to think of an xml document as tree structure where there is top element (hereperson)and other tags ( phoneare drawn as children of their parent elements
6,592
using web services person name phone email type=intl chuck hide=yes + figure tree representation of xml parsing xml here is simple application that parses some xml and extracts some data elements from the xmlimport xml etree elementtree as et data ''chuck + ''tree et fromstring(dataprint('name:'tree find('name'textprint('attr:'tree find('email'get('hide')codethe triple single quote (''')as well as the triple double quote (""")allow for the creation of strings that span multiple lines calling fromstring converts the string representation of the xml into "treeof xml elements when the xml is in treewe have series of methods we can call to extract portions of data from the xml string the find function searches through the xml tree and retrieves the element that matches the specified tag namechuck attryes using an xml parser such as elementtree has the advantage that while the xml in this example is quite simpleit turns out there are many rules regarding
6,593
valid xmland using elementtree allows us to extract data from xml without worrying about the rules of xml syntax looping through nodes often the xml has multiple nodes and we need to write loop to process all of the nodes in the following programwe loop through all of the user nodesimport xml etree elementtree as et input '' chuck brent ''stuff et fromstring(inputlst stuff findall('users/user'print('user count:'len(lst)for item in lstprint('name'item find('name'textprint('id'item find('id'textprint('attribute'item get(' ')codethe findall method retrieves python list of subtrees that represent the user structures in the xml tree then we can write for loop that looks at each of the user nodesand prints the name and id text elements as well as the attribute from the user node user count name chuck id attribute name brent id attribute
6,594
using web services it is important to include all parent level elements in the findall statement except for the top level element ( users/userotherwisepython will not find any desired nodes import xml etree elementtree as et input '' chuck brent ''stuff et fromstring(inputlst stuff findall('users/user'print('user count:'len(lst)lst stuff findall('user'print('user count:'len(lst )lst stores all user elements that are nested within their users parent lst looks for user elements that are not nested within the top level stuff element where there are none user count user count javascript object notation json the json format was inspired by the object and array format used in the javascript language but since python was invented before javascriptpython' syntax for dictionaries and lists influenced the syntax of json so the format of json is nearly identical to combination of python lists and dictionaries here is json encoding that is roughly equivalent to the simple xml from above"name"chuck""phone"type"intl""number"+
6,595
}"email"hide"yesyou will notice some differences firstin xmlwe can add attributes like "intlto the "phonetag in jsonwe simply have key-value pairs also the xml "persontag is gonereplaced by set of outer curly braces in generaljson structures are simpler than xml because json has fewer capabilities than xml but json has the advantage that it maps directly to some combination of dictionaries and lists and since nearly all programming languages have something equivalent to python' dictionaries and listsjson is very natural format to have two cooperating programs exchange data json is quickly becoming the format of choice for nearly all data exchange between applications because of its relative simplicity compared to xml parsing json we construct our json by nesting dictionaries and lists as needed in this examplewe represent list of users where each user is set of key-value pairs ( dictionaryso we have list of dictionaries in the following programwe use the built-in json library to parse the json and read through the data compare this closely to the equivalent xml data and code above the json has less detailso we must know in advance that we are getting list and that the list is of users and each user is set of key-value pairs the json is more succinct (an advantagebut also is less self-describing ( disadvantageimport json data ''"id" "" " ""name"chuck"id" "" " ""name"brent]''info json loads(dataprint('user count:'len(info)for item in infoprint('name'item['name']
6,596
using web services print('id'item['id']print('attribute'item[' ']codeif you compare the code to extract data from the parsed json and xml you will see that what we get from json loads(is python list which we traverse with for loopand each item within that list is python dictionary once the json has been parsedwe can use the python index operator to extract the various bits of data for each user we don' have to use the json library to dig through the parsed jsonsince the returned data is simply native python structures the output of this program is exactly the same as the xml version above user count name chuck id attribute name brent id attribute in generalthere is an industry trend away from xml and towards json for web services because the json is simpler and more directly maps to native data structures we already have in programming languagesthe parsing and data extraction code is usually simpler and more direct when using json but xml is more selfdescriptive than json and so there are some applications where xml retains an advantage for examplemost word processors store documents internally using xml rather than json application programming interfaces we now have the ability to exchange data between applications using hypertext transport protocol (httpand way to represent complex data that we are sending back and forth between these applications using extensible markup language (xmlor javascript object notation (jsonthe next step is to begin to define and document "contractsbetween applications using these techniques the general name for these application-to-application contracts is application program interfaces (apiswhen we use an apigenerally one program makes set of services available for use by other applications and publishes the apis ( the "rules"that must be followed to access the services provided by the program when we begin to build our programs where the functionality of our program includes access to services provided by other programswe call the approach service-oriented architecture (soaa soa approach is one where our overall application makes use of the services of other applications non-soa approach is where the application is single standalone application which contains all of the code necessary to implement the application
6,597
we see many examples of soa when we use the web we can go to single web site and book air travelhotelsand automobiles all from single site the data for hotels is not stored on the airline computers insteadthe airline computers contact the services on the hotel computers and retrieve the hotel data and present it to the user when the user agrees to make hotel reservation using the airline sitethe airline site uses another web service on the hotel systems to actually make the reservation and when it comes time to charge your credit card for the whole transactionstill other computers become involved in the process auto rental service hotel reservation service airline reservation service api api api travel application figure service-oriented architecture service-oriented architecture has many advantagesincluding( we always maintain only one copy of data (this is particularly important for things like hotel reservations where we do not want to over-commitand ( the owners of the data can set the rules about the use of their data with these advantagesan soa system must be carefully designed to have good performance and meet the user' needs when an application makes set of services in its api available over the webwe call these web services security and api usage it is quite common that you need an api key to make use of vendor' api the general idea is that they want to know who is using their services and how much each user is using perhaps they have free and pay tiers of their services or have policy that limits the number of requests that single individual can make during particular time period sometimes once you get your api keyyou simply include the key as part of post data or perhaps as parameter on the url when calling the api
6,598
using web services other timesthe vendor wants increased assurance of the source of the requests and so they expect you to send cryptographically signed messages using shared keys and secrets very common technology that is used to sign requests over the internet is called oauth you can read more about the oauth protocol at www oauth net thankfully there are number of convenient and free oauth libraries so you can avoid writing an oauth implementation from scratch by reading the specification these libraries are of varying complexity and have varying degrees of richness the oauth web site has information about various oauth libraries glossary api application program interface contract between applications that defines the patterns of interaction between two application components elementtree built-in python library used to parse xml data json javascript object notation format that allows for the markup of structured data based on the syntax of javascript objects soa service-oriented architecture when an application is made of components connected across network xml extensible markup language format that allows for the markup of structured data application google geocoding web service google has an excellent web service that allows us to make use of their large database of geographic information we can submit geographical search string like "ann arbormito their geocoding api and have google return its best guess as to where on map we might find our search string and tell us about the landmarks nearby the geocoding service is free but rate limited so you cannot make unlimited use of the api in commercial application but if you have some survey data where an end user has entered location in free-format input boxyou can use this api to clean up your data quite nicely when you are using free api like google' geocoding apiyou need to be respectful in your use of these resources if too many people abuse the servicegoogle might drop or significantly curtail its free service you can read the online documentation for this servicebut it is quite simple and you can even test it using browser by typing the following url into your browsermake sure to unwrap the url and remove any spaces from the url before pasting it into your browser the following is simple application to prompt the user for search stringcall the google geocoding apiand extract information from the returned json
6,599
import urllib requesturllib parseurllib error import json import ssl api_key false if you have google places api keyenter it here api_key 'aizasy___idbyt if api_key is falseapi_key serviceurl 'else serviceurl 'ignore ssl certificate errors ctx ssl create_default_context(ctx check_hostname false ctx verify_mode ssl cert_none while trueaddress input('enter location'if len(address break parms dict(parms['address'address if api_key is not falseparms['key'api_key url serviceurl urllib parse urlencode(parmsprint('retrieving'urluh urllib request urlopen(urlcontext=ctxdata uh read(decode(print('retrieved'len(data)'characters'tryjs json loads(dataexceptjs none if not js or 'statusnot in js or js['status'!'ok'print('===failure to retrieve ===='print(datacontinue print(json dumps(jsindent= )lat js['results'][ ]['geometry']['location']['lat'lng js['results'][ ]['geometry']['location']['lng'print('lat'lat'lng'lnglocation js['results'][ ]['formatted_address'print(location