id
int64
0
25.6k
text
stringlengths
0
4.59k
5,900
okwe've now added six records to our database table let' run an sql query to see how we didcurs execute('select from people'curs fetchall([('bob''dev' )('sue''mus' )('ann''mus' )('tom''mgr' )('kim''adm' )('pat''dev' )run an sql select statement with cursor object to grab all rows and call the cursor' fetchall to retrie...
5,901
names [rec[ for rec in curs fetchall()names ['bob''sue''ann''tom''kim''pat'the fetchall call we've used so far fetches the entire query result table all at onceas single sequence (an empty sequence comes backif the result is emptythat' convenientbut it may be slow enough to block the caller temporarily for large result...
5,902
[naturallywe can do more than fetch an entire tablethe full power of the sql language is at your disposal in pythoncurs execute('select namejob from people where pay 'curs fetchall([('sue''mus')('tom''mgr')('pat''dev')the last query fetches name and job fields for people who earn more than $ , the next is similarbut pa...
5,903
curs execute('delete from people where pay >?',( ,)curs execute('select from people'curs fetchall([('sue''mus' )('ann''mus' )('kim''adm' )conn commit(finallyremember to commit your changes to the database before exiting pythonassuming you wish to keep them without commita connection rollback or close callas well as the...
5,904
colnames [desc[ for desc in curs descriptioncolnames ['name''job''pay'for row in curs fetchall()for namevalue in zip(colnamesrow)print(name'\ =>'valueprint(name =sue job =mus pay = name job pay =ann =mus = name job pay =kim =adm = notice how tab character is used to try to make this output aligna better approach might ...
5,905
rowdicts[ {'pay' 'job''mus''name''sue'and finallya list comprehension will do the job of collecting the dictionaries into list--not only is this less to typebut it probably runs quicker than the original versioncurs execute('select from people'colnames [desc[ for desc in curs descriptionrowdicts [dict(zip(colnamesrow)f...
5,906
return rowdicts if __name__ ='__main__'self test import sqlite conn sqlite connect('dbase 'cursor conn cursor(query 'select namepay from people where pay ?lowpay makedicts(cursorquery[ ]for rec in lowpayprint(recas usualwe can run this file from the system command line as script to invoke its self-test code\pp \dbase\s...
5,907
from sqlite import connect conn connect('dbase 'curs conn cursor(trycurs execute('drop table people'exceptpass did not exist curs execute('create table people (name char( )job char( )pay int( ))'curs execute('insert into people values (???)'('bob''dev' )curs execute('insert into people values (???)'('sue''dev' )curs ex...
5,908
one of the nice things about using python in the database domain is that you can combine the power of the sql query language with the power of the python generalpurpose programming language they naturally complement each other loading with sql and python supposefor examplethat you want to load database table from flat ...
5,909
and python (againsome irrelevant output lines are omitted here) :\pp \dbase\sqlpython from sqlite import connect conn connect('dbase 'curs conn cursor(curs execute('delete from people'curs execute('select from people'curs fetchall([empty the table file open('data txt'rows [line rstrip(split(','for line in filerows[ ['b...
5,910
result curs fetchall(result (('bob' )('ann' )('kim' )tot for (namepayin resulttot +pay print('total:'tot'average:'tot len(result)total average use /to truncate or we can use more advanced tools such as comprehensions and generator expressions to calculate sumsaveragesmaximumsand the likeprint(sum(rec[ for rec in result...
5,911
set is arbitrarily extensible with functionsmodulesand classes to illustratehere are some of the same operations coded in more mnemonic fashion with the dictionaryrecord module we wrote earlierfrom makedicts import makedicts recs makedicts(curs"select from people where job 'devel'"print(len(recs)recs[ ] {'pay' 'job''de...
5,912
""load table from comma-delimited text fileequivalent to this nonportable sqlload data local infile 'data txtinto table people fields terminated by ','""import sqlite conn sqlite connect('dbase 'curs conn cursor(file open('data txt'rows [line rstrip(split(','for line in filefor rec in rowscurs execute('insert into peop...
5,913
for the insert statement (see its comments for the transforms appliedwe could also use an executemany call as we did earlierbut we want to be general and avoid hardcoding the fields insertion template--this function might be used for tables with any number of columns this file also defines login function to automate th...
5,914
if '-in cmdargsformat true cmdargs remove('-'if cmdargsdbname cmdargs pop( if cmdargstable cmdargs[ format if '-in cmdline args dbname if other cmdline arg from loaddb import login conncurs login(dbnamedumpdb(curstableformatwhile we're at itlet' code some utility scripts to initialize and erase the databaseso we do not...
5,915
if input('are you sure?'lower(not in (' ''yes')sys exit(dbname sys argv[ if len(sys argv else 'dbase table sys argv[ if len(sys argv else 'peoplefrom loaddb import login conncurs login(dbnamecurs execute('delete from table#print(curs rowcount'records deleted'conn commit(conn closed by its __del__ else rows not really d...
5,916
display)\pp \dbase\sqldumpdb py testdb ('bob''developer' ('sue''music' ('ann''manager' \pp \dbase\sqldumpdb py testdb records pay = job =developer name =bob pay = job =music name =sue pay = job =manager name =ann the dump script is an exhaustive displayto be more specific about which records to viewuse the query script...
5,917
rows loaded \pp \dbase\sqldumpdb py testdb ('bob''devel' ('sue''music' ('ann''devel' ('tim''admin' ('kim''devel' in closinghere are three queries in action on this new data setthey fetch names of developersjobs that pay above an amountand records with given pay level sorted by job we could run these at the python inter...
5,918
we may need to revert to typing sql commands in client--part of the reason sql is language is because it must support so much generality further extensions to these scripts are left as exercises change this code as you likeit' pythonafter all sql resources although the examples we've seen in this section are simplethei...
5,919
quick look at how you might use it to create and process database records in the sqlobject system in briefsqlobject mapspython classes to database tables python class instances to rows in the table python instance attributes to row columns for exampleto create tablewe define it with classwith class attributes that defi...
5,920
is functionally similar for more details on orms for pythonconsult your friendly neighborhood web search engine you can also learn more about such systems by their roles in some larger web development frameworksdjangofor instancehas an orm which is another variation on this theme pyforma persistent object viewer (exter...
5,921
like thisfrom pp dbase testdata inport actor from formgui import formgui from formtable import shelveofinstance testfile /data/shelvetable shelveofinstance(testfileactorformgui(tablemainloop(table close(run in tablebrowser dir external filename wrap shelf in table object close needed for some dbm figure - captures the ...
5,922
pyform overview material from the third edition in pdf file pyform' source code files are ported to python formthough code in the overview document still shows its third edition roots for the purposes of the published portions of this booklet' move on to the next and our next tools topicdata structure implementations d...
5,923
data structures "roses are redviolets are bluelists are mutableand so is set foodata structures are central theme in most programseven if python programmers often don' need to care their apathy is warranted--python comes "out of the boxwith rich set of built-in and already optimized types that make it easy to deal with...
5,924
types coded in use patterns similar to those here in the endthoughwe'll also see that python' built-in support can often take the place of homegrown solutions in this domain although custom data structure implementations are sometimes necessary and still have much to offer in terms of code maintenance and evolutionthey...
5,925
top is end-of-list top is front-of-list top is front-of-list pop top stack[- ]top stack[ ]top stack[ ]del stack[- del stack[ stack[: [even more convenientlypython grew list pop method later in its life designed to be used in conjunction with append to implement stacks and other common structures such as queuesyielding ...
5,926
performswe' have to add code around each hardcoded stack operation in large systemthis update may be nontrivial work as we'll discuss in we may also decide to move stacks to -based implementationif they prove to be performance bottleneck as general rulehardcoded operations on built-in data structures don' support futur...
5,927
the stack is declared global in functions that change itbut not in those that just reference it the module also defines an error object (errorthat can be used to catch exceptions raised locally in this module some stack errors are built-in exceptionsthe method item triggers indexerror for out-of-bounds indexes most of ...
5,928
print(stack item( )end=' stack class perhaps the biggest drawback of the module-based stack is that it supports only single stack object all clients of the stack module effectively share the same stack sometimes we want this featurea stack can serve as shared-memory object for multiple modules but to implement true sta...
5,929
len(instance)not instance def __add__(selfother)return stack(self stack other stackinstance instance def __mul__(selfreps)return stack(self stack repsinstance reps def __getitem__(selfoffset)return self stack[offsetsee also __iter__ instance[ ][ : ]infor def __getattr__(selfname)return getattr(self stacknameinstance so...
5,930
instances by attribute references and expressions additionallyit defines the __get attr__ special method to intercept references to attributes not defined in the class and to route them to the wrapped list object (to support list methodssortappendreverseand so onmany of the module' operations become operators in the cl...
5,931
"customize stack for usage datafrom stack import stack extends imported stack class stacklog(stack)pushes pops def __init__(selfstart=[])self maxlen stack __init__(selfstartcount pushes/popsmax-size shared/static class members could also be module vars def push(selfobject)stack push(selfobjectstacklog pushes + self max...
5,932
some more efficient than others so farour stacks have used slicing and extended sequence assignment to implement pushing and popping this method is relatively inefficientboth operations make copies of the wrapped list object for large stacksthis practice can add significant time penalty one way to speed up such code is...
5,933
so 'inand 'forstop def __repr__(self)return '[faststack:repr(self stack']this class' __getitem__ method handles indexingin testsand for loop iteration as before (when no __iter__ is defined)but this version has to traverse tree to find node by index notice that this isn' subclass of the original stack class since nearl...
5,934
incurs some performance degradation for the extra method callsbut it supports future changes better by encapsulating stack operations example - pp \dstruct\basic\stack py "optimize with in-place list operationsclass error(exception)pass when importedlocal exception class stackdef __init__(selfstart=[])self stack [for i...
5,935
top( timing the improvements the prior section' in-place changes stack object probably runs faster than both the original and the tuple-tree versionsbut the only way to really be sure is to time the alternative implementations since this could be something we'll want to do more than oncelet' first define general module...
5,936
import timer in-place stacksy append(xgeneral function timer utility rept from sys import argv pushespopsitems (int(argfor arg in argv[ :]def stackops(stackclass) stackclass('spam'for in range(pushes) push(ifor in range(items) [ifor in range(pops) pop(make stack object exercise its methods xrange generator or mod __imp...
5,937
done at all--tuples (stack win by hair in the last test case when there is no indexingas in the last testthe tuple and in-place change stacks are roughly six and five times quicker than the simple list-based stackrespectively since pushes and pops are most of what clients would normally do to stacktuples are contender ...
5,938
who do both activities by intersecting the two sets union of such sets would contain either type of individualbut would include any given individual only once this latter property also makes sets ideal for removing duplicates from collections--simply convert to and from set to filter out repeats in factwe relied on suc...
5,939
{'eggs''ham''spam'plus there are additional operations we won' illuminate here--see core language text such as learning python for more details for instancebuilt-in sets also support operations such as superset testingand they come in two flavorsmutable and frozen (frozen sets are hashableand thus usable in sets of set...
5,940
return res these functions work on any type of sequence--lists stringstuplesand other iterable objects that conform to the protocols expected by these functions (for loopsin membership testsin factwe can even use them on mixed object typesthe last two commands in the following test compute the intersection and union of...
5,941
but they also support three or more operands notice the use of an else on the intersection' for loop here to detect common items also note that the last two examples in the following session work on lists with embedded compound objectsthe in tests used by the intersect and union functions apply equality testing to sequ...
5,942
res self data[:for in otherif not in resres append(xreturn set(resdef concat(selfvalue)for in valueif not in self dataself data append(xmake copy of my list valuea liststringset filters out duplicates def __len__(self)return len(self datadef __getitem__(selfkey)return self data[keydef __and__(selfother)return self inte...
5,943
dictionariesthe in list scans of the original set can be replaced with direct dictionary fetches in this scheme in traditional termsmoving sets to dictionaries replaces slow linear searches with fast hashtable fetches computer scientist would explain this by saying that the repeated nested scanning of the list-based in...
5,944
from fastset import set users set(['bob''emily''howard''peeper']users set(['jerry''howard''carol']users set(['emily''carol']users users users users users users users (users users users users data {'peeper'none'bob'none'howard'none'emily'nonethe main functional difference in this version is the order of items in the set...
5,945
fastset set([( )( )]timing the results under python so how did we do on the optimization front this timeagainguesses aren' usually good enoughthough algorithmic complexity seems compelling piece of evidence here to be sureexample - codes script to compare set class performance it reuses the timer module of example - us...
5,946
for this specific test casethe dictionary-based set implementation (fastestis roughly three times faster than the simple list-based set (setin factthis threefold speedup is probably sufficient python dictionaries are already optimized hashtables that you might be hard-pressed to improve on unless there is evidence that...
5,947
extract named fields from the tuples in table difference remove one set' tuples from another these operations go beyond the tools provided by python' built-in set objectand are prime example of why you may wish to implement custom set type in the first place although have ported this code to run under python xi have no...
5,948
res [for in selfif in otherres append(xreturn set(resother is any sequence type self is the instance subject def union(selfother)res set(selfres concat(otherreturn res return new set def concat(selfvalue)for in valueif not in selfself append(xnew set with copy of my list insert uniques from other valuea liststringset f...
5,949
sections binary search trees binary trees are data structure that impose an order on inserted nodesitems less than node are stored in the left subtreeand items greater than node are inserted in the right at the bottomthe subtrees are empty because of this structurebinary trees naturally support quickrecursive traversal...
5,950
set( { set constructor {kk+ for in { dict(zip( [ len( )){ dict fromkeys( { dict comprehension dict constructor dict method so why bother with custom search data structure implementation heregiven such flexible built-insin some applicationsyou might notbut here especiallya custom implementation often makes sense to allo...
5,951
def __repr__(self)return '*def lookup(selfvalue)return false def insert(selfvalue)return binarynode(selfvalueselfclass binarynodedef __init__(selfleftvalueright)self dataself leftself right fail at the bottom add new node at bottom valueleftright def lookup(selfvalue)if self data =valuereturn true elif self data valuer...
5,952
* ) * ) * * * ) * * * ) * ) at the end of this we'll see another way to visualize such trees in gui named pytree (you're invited to flip ahead now if you prefernode values in this tree object can be any comparable python object--for instancehere is tree of stringsz binarytree(for in 'badce' insert(cz *' ')' '*' ')' '*'...
5,953
def __repr__(self)return '*def lookup(selfkey)return none def insert(selfkeyval)return binarynode(selfkeyvalselffail at the bottom add node at bottom class binarynodedef __init__(selfleftkeyvalright)self keyself val keyval self leftself right leftright def lookup(selfkey)if self key =keyreturn self val elif self key ke...
5,954
built-in gangthoughwe need to move on to the next section graph searching many problems that crop up in both real life and real programming can be fairly represented as graph-- set of states with transitions ("arcs"that lead from one state to another for exampleplanning route for trip is really graph search problem in ...
5,955
we'll use to run few searches in the graph example - pp \dstruct\classics\gtestfunc py "dictionary based graph representationgraph {' '' '' '' '' '' '' '[' '' '' '][' '][' '' '][' '][' '' '' ']][' ' directedcyclic graph stored as dictionary 'keyleads-to [nodesdef tests(searcher)test searcher function print(searcher(' '...
5,956
"graph searchusing paths stack instead of recursiondef search(startgoalgraph)solns generate(([start][])goalgraphsolns sort(key=lambda xlen( )return solns def generate(pathsgoalgraph)solns [while pathsfrontpaths paths state front[- if state =goalsolns append(frontelsefor arc in graph[state]if arc not in frontpaths (fron...
5,957
and code to see how moving graphs to classes using dictionaries to represent graphs is efficientconnected nodes are located by fast hashing operation but depending on the applicationother representations might make more sense for instanceclasses can be used to model nodes in networktoomuch like the binary tree example ...
5,958
=graph(' ')and so onexample - pp \dstruct\classics\gtestobj py "build class-based graph and run test searchesfrom graph import graph this doesn' work inside def in undefined for name in "abcdefg"exec("% graph('% ')(namename) arcs [begb arcs [cc arcs [ded arcs [fe arcs [cfgg arcs [amake objects first label=variable-name...
5,959
scratched the surface of this academic yet useful domain hereexperiment further on your ownand see other books for additional topics ( breadth-first search by levelsand best-first search by path or state scores) :\pp \dstruct\classicspython gtestobj py [[sm][spm][spam]permuting sequences our next data structure topic i...
5,960
pick list[ : + rest list[:ilist[ + :for in subset(restsize- )result append(pick xreturn result def combo(listsize)if size = or not listreturn [list[: ]elseresult [for in range( (len(listsize )pick list[ : + rest list[ + :for in combo(restsize )result append(pick xreturn result sequence slice keep [:ipart order doesn' m...
5,961
for in range( )print(icombo("help" ) ['' [' '' '' '' ' ['he''hl''hp''el''ep''lp' ['hel''hep''hlp''elp' ['help' [finallysubset is just fixed-length permutationsorder mattersso the result is larger than for combo in factcalling subset with the length of the sequence is identical to permutesubset([ ] [[ ][ ][ ][ ][ ][ ]su...
5,962
reversal of collections can be coded either recursively or iteratively in pythonand as functions or class methods example - is first attempt at two simple reversal functions example - pp \dstruct\classics\rev py def reverse(list)recursive if list =[]return [elsereturn reverse(list[ :]list[: def ireverse(list)iterative ...
5,963
return reverse(list[ :]list[: def ireverse(list)res list[: for in range(len(list))res list[ : + res return res add front item on the end emptyof same type add each item to front the combination of the changes allows the new functions to work on any sequenceand return new sequence of the same type as the sequence passed...
5,964
last sort tuplesc:\pp \dstruct\classicspython sort py [{'age' 'name''doe'}{'age' 'name''john'}[{'age' 'name''john'}{'age' 'name''doe'}[('doe' )('john' )[('john' )('doe' )adding comparison functions since functions can be passed in like any other objectwe can easily allow for an optional comparison function in the next ...
5,965
accomplish what we just did the hard waybuilt-in sorting tools python' two built-in sorting tools are so fast that you would be hard-pressed to beat them in most scenarios to use the list object' sort method for arbitrary kinds of iterablesconvert first if neededtemp list(sequencetemp sort(use items in temp alternative...
5,966
will often prove better choice in the end make no mistakesometimes you really do need objects that add functionality to builtin types or do something more custom the set classes we metfor instancecan add custom tools not directly supported by python todaybinary search trees may support some algorithms better than dicti...
5,967
it is written with python and tkinterit should be portable to windowsunixand macs at the topit' used with code of this formroot tk(bwrapper binarytreewrapper(pwrapper parsetreewrapper(viewer treeviewer(bwrapperrootbuild single viewer gui add extrasinput linetest btns make wrapper objects start out in binary mode def on...
5,968
to save real estate here to study pytreesee the following directoryc:\pp \dstruct\treeview also like pyformthe documentation directory there has the original description of this example that appeared in the third edition of this bookpytree' code is in python formbut the third edition overview may not be as mentionedpyt...
5,969
text and language "see jack hack hackjackhackin one form or anotherprocessing text-based information is one of the more common tasks that applications need to perform this can include anything from scanning text file by columns to analyzing statements in language defined by formal grammar such processing usually is cal...
5,970
xml and html text parsing parsersgrammars custom language parsersboth handcoded and generated embedding running python code with eval and exec built-ins and more natural language processing for simpler taskspython' built-in string object is often all we really need python strings can be indexedconcatenatedslicedand pro...
5,971
'spam "{ :< }"{ :+ }format('ham''spam "ham "+ these operations are covered in core language resources such as learning python for the purposes of this thoughwe're interested in more powerful toolspython' string object methods include wide variety of text-processing utilities that go above and beyond string expression o...
5,972
strings the latter makes them applicable to arbitrarily encoded unicode textsimply because the str type is unicode texteven if it' only ascii these methods originally appeared as function in the string modulebut are only object methods todaythe string module is still present because it contains predefined constants ( s...
5,973
template string template('---$key ---$key ---'template substitute(vals'---spam---shrubbery---template substitute(key ='brian'key ='loretta''---brian---loretta---see the library manual for more on this extension although the string datatype does not itself support the pattern-directed text processing that we'll meet lat...
5,974
let' look next at some practical applications of string splits and joins in many domainsscanning files by columns is fairly common task for instancesuppose you have file containing columns of numbers output by another systemand you need to sum each column' numbers in pythonstring splitting is the core operation behind ...
5,975
len('abc'[ , , ][ {'spam': }['spam' :\pp \langpython summer py table txt [ summing with zips and comprehensions we'll revisit eval later in this when we explore expression evaluators sometimes this is more than we want--if we can' be sure that the strings that we run this way won' contain malicious codefor instanceit m...
5,976
print(open('table txt'read() herewe cannot preallocate fixed-length list of sums because the number of columns may vary splitting on whitespace extracts the columnsand float converts to numbersbut fixed-size list won' easily accommodate set of sums (at leastnot without extra code to manage its sizedictionaries are more...
5,977
list of words or variables separated by spacesvariables start with to use ruleit is translated to an internal form-- dictionary with nested lists to display ruleit is translated back to the string form for instancegiven the callrules internal_rule('rule if ?xb then cd ? 'the conversion in function internal_rule proceed...
5,978
return 'join(join(clausefor clause in conjunctto produce the desired nested lists and string by combining two steps into one this form might run fasterwe'll leave it to the reader to decide whether it is more difficult to understand as usualwe can test components of this module interactivelyimport rules rules internal(...
5,979
(and souls brave enough to try the portlesson prototype and migrate if you care about performancetry to use the string object' methods rather than things such as regular expressions whenever you can although this is broad rule of thumb and can vary from release to releasesome string methods may be faster because they h...
5,980
strings supply pattern and string and ask whether the string matches your pattern after matchparts of the string matched by parts of the pattern are made available to your script that ismatches not only give yes/no answerbut also can pick out substrings as well regular expression pattern strings can be complicated (let...
5,981
re-interactive txt for all the interactive code run in this section)text 'hello spam worldtext 'hello spam otherthe match performed in the following code does not precompileit executes an immediate match to look for all the characters between the words hello and world in our text stringsimport re matchobj re match('hel...
5,982
letter ([ww])as you can seepatterns can handle wide variations in datapatt '\ ]*hello\ ]+*)[ww]orldline hello spamworldmobj re match(pattlinemobj group( 'spamnotice that we matched str pattern to str string in the last listing we can also match bytes to bytes in order to handle data such as encoded textbut we cannot mi...
5,983
substring group (split treats groups specially)import re re split('--''aaa--bbb--ccc'['aaa''bbb''ccc're sub('--'''aaa--bbb--ccc''aaa bbb cccsingle string case re split('--|==''aaa--bbb==ccc'['aaa''bbb''ccc're sub('--|=='''aaa--bbb==ccc''aaa bbb cccsplit on -or =replace -or =re split('[-=]''aaa-bbb=ccc'['aaa''bbb''ccc's...
5,984
between'//find('ham'find substring offset re findall('''//'find all matches/groups ['spam''ham''eggs're findall('''['spam''ham''eggs're findall('/?'''[('spam''ham')('eggs''cheese')re search('/?''todays menu'groups(('spam''ham'especially when using findallthe (?soperator comes in handy to force to match end-of-line char...
5,985
line split(['aaa''bbb''ccc're split(+'line['aaa''bbb''ccc're findall('[]+'line['aaa''bbb''ccc'line 'aaa bbb-ccc ddd -/ & *ere findall('[\-/]+'line['aaa''bbb''ccc''ddd'' & * 'split data with fixed delimiters split on general delimiters find non-delimiter runs handle generalized text at this pointif you've never used pat...
5,986
split string by occurrences of pattern if capturing parentheses (()are used in the patternthe text of all groups in the pattern are also returned in the resulting list sub(patternreplstring [countflags]return the string obtained by replacing the (first countleftmost nonoverlapping occurrences of pattern ( string or pat...
5,987
returns tuple of all groupssubstrings of the match (for group numbers and highergroupdict(returns dictionary containing all named groups of the match (see (?prsyntax aheadstart([group]end([group]indices of the start and end of the substring matched by group (or the entire matched stringif no group is passedspan([group]...
5,988
interpretation | alternativematches left or right rr concatenationmatch both rs (rmatches any regular expression inside ()and delimits group (retains matched substring(?:rsame as (rbut simply delimits part and does not denote saved group (?=rlook-ahead assertionmatches if matches nextbut doesn' consume any of the strin...
5,989
sequence interpretation \number matches text of group number (numbered from \ matches only at the start of the string \ empty string at word boundaries \ empty string not at word boundaries \ any decimal digit character ([ - for ascii\ any nondecimal digit character ([^ - for ascii\ any whitespace character (\ \ \ \ \v...
5,990
selection sets print(re search(* [de][ - ][^ -ze] \ ?"abcdefg\ "start()alternativesr | means or print(re search("( | )( | )( | ) "aycd "start()test each char print(re search("(?: | )(?: | )(?: | ) "aycd "start()samenot saved print(re search(" |xb|yc|zd"aycd "start()matches just aprint(re search("( |xb|yc|zd)ycd"aycd "s...
5,991
and fourth tests shows how alternatives can be grouped by both position and nameand the last test matches #define lines--more on this pattern in momentc:\pp \langpython re-groups py (' '' '' '(' '' '' '{' '' '' '' '' '' '('spam'' 'finallybesides matches and substring extractionre also includes tools for string replacem...
5,992
"scan header files to extract parts of #define and #include linesimport sysre pattdefine re compile'^#[\ ]*define[\ ]+(\ +)[\ ]**)'pattinclude re compile'^#[\ ]*include[\ ]+[<"]([\ /]+)'compile to pattobj "define xxx yyy \ like [ -za- - "include def scan(fileobj)count for line in fileobjscan by linesiterator count + ma...
5,993
defined test_h include stdio include lib/spam include python defined debug defined hello 'hello regex world defined spam defined eggs sunny side up defined adder (arg arg for an additional example of regular expressions at worksee the file pygrep py in the book examples packageit implements simple pattern-based "grepfi...
5,994
client and server sides of the xml-rpc protocol (remote procedure calls that transmit objects encoded as xml over http)as well as standard html parserhtml parserthat works on similar principles and is presented later in this the third-party domain has even more xml-related toolsmost of these are maintained separately f...
5,995
titles by exampleusing each of the four primary python tools at our disposal--patternssaxdomand elementtree regular expression parsing in some contextsthe regular expressions we met earlier can be used to parse information from xml files they are not complete parsersand are not very robust or accurate in the presence o...
5,996
""xml parsingsax is callback-based api for intercepting parser events ""import xml saxxml sax handlerpprint class bookhandler(xml sax handler contenthandler)def __init__(self)self intitle false self mapping {def startelement(selfnameattributes)if name ="book"self buffer "self isbn attributes["isbn"elif name ="title"sel...
5,997
{'- ''python xml''- ''python cookbook nd edition''- ''python in nutshell nd edition''- ''learning python th edition''- ''python pocket reference th edition''- ''programming python th edition'dom parsing the dom parsing model for xml is perhaps simpler to understand--we simply traverse tree of objects after the parse--b...
5,998
'- ''python in nutshell nd edition''- ''learning python th edition''- ''python pocket reference th edition''- ''programming python th edition'elementtree parsing as fourth optionthe popular elementtree package is standard library tool for both parsing and generating xml as parserit' essentially more pythonic type of do...
5,999
naturallythere is much more to python' xml support than these simple examples imply in deference to spacethoughhere are pointers to xml resources in lieu of additional examplesstandard library firstbe sure to consult the python library manual for more on the standard library' xml support tools see the entries for rexml...