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 ra...
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 i...
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 tr...
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 compariso...
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''...
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 spa...
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 wer...
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 spot...
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 ...
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 proper...
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...
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)w...
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 : : retur...
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 ...
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()...
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 foll...
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 lin...
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...
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 (...
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...
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 ...
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 wan...
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 blad...
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 ord...
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...
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...
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 [' '' '...
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 num...
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 u...
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 sp...
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 sam...
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 i...
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 ...
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 i...
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 progra...
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-probabil...
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...
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 [...
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-v...
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 ...
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 usi...
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 ...
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[wor...
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 'ch...
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 ...
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 ...
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 "co...
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@...
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...
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 ...
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 us...
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 f...
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 ...
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 assignmen...
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(''''strin...
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 cr...
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 f...
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-s...
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...
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 tha...
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 sp...
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 th...
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 addresse...
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'['...
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 express...
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...
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 ...
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 whil...
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 ma...
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 " "" "" "" "o...
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 interactiv...
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 c...
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 ...
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 ...
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 y...
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 inst...
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 f...
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 la...
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 requestur...
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 requ...
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...
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 librar...
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 t...
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 beauti...
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 m...
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 applica...
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 tha...
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'textprin...
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 in...
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...
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...
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 us...
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...
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 protoco...
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...