id
int64
0
25.6k
text
stringlengths
0
4.59k
6,400
parameters filenamea file path librarychoose specific pyexcel-io plugin for writing renderer_librarychoose pyexcel parser plugin for writing parameters related to csv file format for csvfmtparams are accepted delimiter field separator lineterminator line terminator encodingcsv specific specify the file encoding the csv...
6,401
pyexcel sheet save_to_django_model sheet save_to_django_model(modelinitializer=nonemapdict=nonebatch_size=nonesave to database table through django model parameters model database model initializer initialization functions for your model mapdict custom map dictionary for your data columns batch_size parameter to django...
6,402
table continued from previous page extend_columns(columnsinserts two dimensional data after the rightmost column extend_columns_with_rows(rowsrows were appended to the rightmost side extend_rows(rowsinserts two dimensional data after the bottom row filter([column_indicesrow_indices]apply the filter with immediate effec...
6,403
table continued from previous page register_presentation(file_type[]partial(func*args**keywordsnew function with partial application of the given arguments and keywords reverse(opposite to enumerate row_at(indexgets the data at the specified row row_range(utility function to get row range rows(returns top to bottom row...
6,404
transpose(vertical(table continued from previous page rotate the data table by degrees default iterator to go through each cell one by one from leftmost column to rightmost row and from top to bottom example attributes array bookdict csv csvz dict fods matrix grid handsontable handsontable_html html matrix json matrix ...
6,405
if you would like to do custom rendering for each row of the two dimensional datayou would need to pass row formatting/rendering function to the parameter "rendererof pyexcel' signature functions __init__(namepayloadinitialize self see help(type(self)for accurate signature methods __init__(namepayloadget_internal_array...
6,406
table "example csv above column manipulation can be performed on rows similarly this section will not repeat the same example but show some advance usages import pyexcel as pe data [[ , , ][ , , ][ , , ] pe internal sheets matrix(datam row[ : [[ ][ ] row[ : [ row[ [ del row[ : row[ [ __init__(matrixinitialize self see ...
6,407
(continued from previous pagem column[ [ column[ [ column[ [ del column[ column[ [ column[ traceback (most recent call last)indexerror __init__(matrixinitialize self see help(type(self)for accurate signature methods __init__(matrixformat([column_indexformatterformat_specs]get_converter(theformatterselect(indicesinitial...
6,408
how to test your contribution although nose and doctest are both used in code testingit is adviable that unit tests are put in tests doctest is incorporated only to make sure the code examples in documentation remain valid across different development releases on linux/unix systemsplease launch your tests like thismake...
6,409
(continued from previous pagelevel=info handlers=consolehandler [logger_sourceslevel=debug handlers=consolehandler qualname=pyexcel sources factory propagate= [logger_rendererslevel=debug handlers=consolehandler qualname=pyexcel renderers factory propagate= [handler_consolehandlerclass=streamhandler level=debug formatt...
6,410
(continued from previous page--hidden-import pyexcel plugins renderers _texttable --hidden-import pyexcel plugins parsers excel --hidden-import pyexcel plugins parsers sqlalchemy --hidden-import pyexcel plugins sources http --hidden-import pyexcel plugins sources file_input --hidden-import pyexcel plugins sources memor...
6,411
yehua yehua will walk you through creating pyexcel package press ^ to quit at any time what is your project namepyexcel-pdfr what is the descriptionparses tables in pdf file as tabular data what is project type pyexcel plugins command line interface python' externsion ( , , ) what is the nick namepdf step call moban to...
6,412
what' breaking in in the following statementssheet_a sheet row rows sheet_b sheet column columns book sheet_a sheet_b sheet_a and sheet_b will no longer have access to the data of sheet book will no longer have access to the data of sheet_a and sheet_b under hyrum' lawthis enhancement in will cause breakage otherwise w...
6,413
(continued from previous page+--- +---oryou could do thisdata [' '][' '][' ']sheet pe sheet(datadef odd_filter(row_index_)return row_index = del sheet row[odd_filtersheet pyexcel sheet+--- +---and the same applies to evenrowfilteroddcolumnfilterevencolumnfilter updated format function replacement of sheetformatter the ...
6,414
can be replaced bysheet column format(["column ""column "]strmigrate from to explicit importsno longer needed please forget about these statementsimport pyexcel ext xls import pyexcel ext ods import pyexcel ext xlsx they are no longer needed as long as you have pip-installed themthey will be auto-loaded howeverif you d...
6,415
pyexcel writer("afile csv"data=[[' '' '' '' '' '' '' '' '' '' ' ] write_array(tablew close(the new code isdata=[[' '' '' '' '' '' '' '' '' '' ' ]pyexcel save_as(array=datadest_file_name="afile csv"here is another piece of legacy codecontent " "[ , , , , ]" "[ , , , , ]" "[ , , , , ] pyexcel writer("afile csv" write_dic...
6,416
import pyexcel content "sheet "[[ ][ ][ ]]"sheet "[[ ][ ][ ]]"sheet "[[ ' ' ' ' ' '][ ][ ][ ] pyexcel bookwriter("afile csv" write_book_from_dict(contentw close(the replacement code isimport pyexcel content "sheet "[[ ][ ][ ]]"sheet "[[ ][ ][ ]]"sheet "[[ ' ' ' ' ' '][ ][ ][ ]pyexcel save_book_as(bookdict=contentdest_f...
6,417
updated # book created from dict no longer discards order fixed # remove leading and trailing whitespace for column names removed python compatibility have been permanently removed fixed # control the column order when write the data output fixed # texttable was dropped out in as compulsary dependency end user may expe...
6,418
updated # get_sheet {indexerror}list index out of range /xlsx can' be opened updated # include examples in tarbar updated # remove pyexcel-handsontalbe in test add testsand docs folder in distribution updated # please use scan_plugins_regexwhich lml complains about updated dependency on pyexcel-io to updated to require...
6,419
added # sort book sheets updated # dest_sheet_name in save_as will set the sheet name in the output # fix set membership test to run faster in python added pyexcel-io# expose bulk_save to developer removed # remove gease from setup_requiresintroduced by removed testing against python # include license file in manifest ...
6,420
updated embeded the enabler for pyexcel-htmlr http source does not support text/html as mime type updated support saving sheetstream and bookstream to database targets this is needed for pyexcel-webio and its downstream projects added sheet top(and sheet top_left(for data browsing add html as default rich display in ju...
6,421
updated # regression save_to_memory(should have returned stream instance which has been reset to zero if possible the exception is sys stdoutwhich cannot be reset # not able to handle decimal decimal removed remove get_{{file_type}}_stream functions from pyexcel sheet and pyexcel book introduced since added streamattri...
6,422
updated # export_columns is ignored update dependency on pyexcel-io updated # cannot display empty sheet(hence book with empty sheetas texttable updated # optional module import error become visible added file type setters for sheet and bookand its documentation iget_records returns generator for list of records and sh...
6,423
pyexcel sheet named_columns( ~pyexcel sheet save_to_memory and ~pyexcel book save_to_memory return the actual content no longer they will return io object hence you cannot call getvalue(on them removed content and out_file as function parameters to the signature functions are no longer supported sourcefactory and rende...
6,424
freeze_formatters pyexcel sheet filter has been re-implemented and all filters were removedpyexcel formatters sheetformatter updated # texttable should have been made as compulsory requirement updated for python writing to sys stdout by pyexcel-cli raise ioerror updated for python do not seek when saving to memory if s...
6,425
updated adopt pyexcel-io yield key word to return generator as content pyexcel save_as and pyexcel save_book_as get performance improvements added support pyramid-excel which does the database commit on its own added get excel data from http url added support django texttable as default renderer added added sqlalchemy ...
6,426
utilities to get array and dictionary out from excel files cookbok receipes for some common and simple usage of this library change log
6,427
contents asking the user for input comments choosing mnemonic variable names debugging glossary exercises conditional execution boolean expressions logical operators conditional execution alternative execution chained conditionals nested conditionals catching exceptions using try and except short-circuit evaluation of ...
6,428
vii iteration updating variables the while statement infinite loops finishing iterations with continue definite loops using for loop patterns counting and summing loops maximum and minimum loops debugging glossary exercises strings string is sequence getting the length of string using len traversal through string with ...
6,429
contents letting the user choose the file name using tryexceptand open writing files debugging glossary exercises lists list is sequence lists are mutable traversing list list operations list slices list methods deleting elements lists and functions lists and strings parsing lines objects and values aliasing list argum...
6,430
ix tuples tuples are immutable comparing tuples tuple assignment dictionaries and tuples multiple assignment with dictionaries the most common words using tuples as keys in dictionaries sequencesstringslistsand tuples oh my list comprehension debugging glossary exercises regular expressions character matching in regula...
6,431
contents using web services extensible markup language xml parsing xml looping through nodes javascript object notation json parsing json application programming interfaces security and api usage glossary application google geocoding web service application twitter object-oriented programming managing larger programs g...
6,432
xi constraints in database tables retrieve and/or insert record storing the friend relationship three kinds of keys using join to retrieve data summary debugging glossary visualizing data building openstreetmap from geocoded data visualizing networks and interconnections visualizing mail data contributions contributor ...
6,433
why should you learn to write programswriting programs (or programmingis very creative and rewarding activity you can write programs for many reasonsranging from making your living to solving difficult data analysis problem to having fun to helping someone else solve problem this book assumes that everyone needs to kno...
6,434
why should you learn to write programsfor examplelook at the first three paragraphs of this and tell me the most commonly used word and how many times the word is used while you were able to read and understand the words in few secondscounting them is almost painful because it is not the kind of problem that human mind...
6,435
computer hardware architecture before we start learning the language we speak to give instructions to computers to develop softwarewe need to learn small amount about how computers are built if you were to take apart your computer or cell phone and look deep insideyou would find the following partssoftware input and ou...
6,436
why should you learn to write programsas programmeryour job is to use and orchestrate each of these resources to solve the problem that you need to solve and analyze the data you get from the solution as programmer you will mostly be "talkingto the cpu and telling it what to do next sometimes you will tell the cpu to u...
6,437
new programming language has very different vocabulary and grammar but the problem-solving skills will be the same across all programming languages you will learn the "vocabularyand "sentencesof python pretty quickly it will take longer for you to be able to write coherent program to solve brand-new problem we teach pr...
6,438
why should you learn to write programsprint('hello world!'and we have even written our first syntactically correct python sentence our sentence starts with the function print followed by string of text of our choosing enclosed in single quotes the strings in the print statements are enclosed in quotes single quotes and...
6,439
print('hello world!'hello worldthis is looking much betterso you try to communicate some moreprint('you must be the legendary god that comes from the sky'you must be the legendary god that comes from the sky print('we have been waiting for you for long time'we have been waiting for you for long time print('our legend s...
6,440
why should you learn to write programsthe proper way to say "good-byeto python is to enter quit(at the interactive chevron prompt it would have probably taken you quite while to guess that oneso having book handy probably will turn out to be helpful terminologyinterpreter and compiler python is high-level language inte...
6,441
print( in this examplewe ask python to remember the value six and use the label so we can retrieve the value later we verify that python has actually remembered the value using print then we ask python to retrieve and multiply it by seven and put the newly computed value in then we ask python to print out the value cur...
6,442
why should you learn to write programsthat is more than you really need to know to be python programmerbut sometimes it pays to answer those little nagging questions right at the beginning writing program typing commands into the python interpreter is great way to experiment with python' featuresbut it is not recommend...
6,443
the clown ran after the car and the car ran into the tent and the tent fell down on the clown and the car then imagine that you are doing this task looking at millions of lines of text frankly it would be quicker for you to learn python and write python program to count the words than it would be to manually scan the w...
6,444
why should you learn to write programspowerful capabilities of python and how to compose those capabilities together to create useful programs there are some low-level conceptual patterns that we use to construct programs these constructs are not just for python programsthey are part of every programming language from ...
6,445
hate you pythonfile ""line hate you pythonsyntaxerrorinvalid syntax if you come out of therei would teach you lesson file ""line if you come out of therei would teach you lesson syntaxerrorinvalid syntax there is little to be gained by arguing with python it is just tool it has no emotions and it is happy and ready to ...
6,446
why should you learn to write programsagain in all three types of errorspython is merely trying its hardest to do exactly what you have asked debugging when python spits out an error or even when it gives you result that is different from what you had intendedthen begins the hunt for the cause of the error debugging is...
6,447
option is to retreatsimplifying the program until you get to something that works and that you understand beginning programmers are often reluctant to retreat because they can' stand to delete line of code (even if it' wrongif it makes you feel bettercopy your program into another file before you start stripping it dow...
6,448
why should you learn to write programshigh-level language programming language like python that is designed to be easy for humans to read and write interactive mode way of using the python interpreter by typing commands and expressions at the prompt interpret to execute program in high-level language by translating it ...
6,449
primt 'hello world!file ""line primt 'hello world!syntaxerrorinvalid syntax exercise where in the computer is variable such as "xstored after the following python line finishesx acentral processing unit bmain memory csecondary memory dinput devices eoutput devices exercise what will the following program print outx pri...
6,450
why should you learn to write programs
6,451
variablesexpressionsand statements values and types value is one of the basic things program works withlike letter or number the values we have seen so far are and "helloworld!these values belong to different types is an integerand "helloworld!is stringso called because it contains "stringof letters you (and the interp...
6,452
variablesexpressionsand statements type(' 'type(' 'they're strings when you type large integeryou might be tempted to use commas between groups of three digitsas in , , this is not legal integer in pythonbut it is legalprint( , , wellthat' not what we expected at allpython interprets , , as commaseparated sequence of i...
6,453
variable names and keywords programmers generally choose names for their variables that are meaningful and document what the variable is used for variable names can be arbitrarily long they can contain both letters and numbersbut they cannot start with number it is legal to use uppercase lettersbut it is good idea to b...
6,454
variablesexpressionsand statements script usually contains sequence of statements if there is more than one statementthe results appear one at time as the statements execute for examplethe script print( print(xproduces the output the assignment statement produces no output operators and operands operators are special s...
6,455
minute minute// in python integer division functions much more as you would expect if you entered the expression on calculator expressions an expression is combination of valuesvariablesand operators value all by itself is considered an expressionand so is variableso the following are all legal expressions (assuming th...
6,456
variablesexpressionsand statements exponentiation has the next highest precedenceso ** + is not and * ** is not ultiplication and division have the same precedencewhich is higher than addition and subtractionwhich also have the same precedence so * - is not and + / is not operators with the same precedence are evaluate...
6,457
second ' print(first second the operator also works with strings by multiplying the content of string by an integer for examplefirst 'test second print(first secondtest test test asking the user for input sometimes we would like to take the value for variable from the user via their keyboard python provides built-in fu...
6,458
variablesexpressionsand statements int(speed int(speed but if the user types something other than string of digitsyou get an errorspeed input(promptwhat is the airspeed velocity of an unladen swallowwhat do you meanan african or european swallowint(speedvalueerrorinvalid literal for int(with base we will see how to han...
6,459
choosing mnemonic variable names as long as you follow the simple rules of variable namingand avoid reserved wordsyou have lot of choice when you name your variables in the beginningthis choice can be confusing both when you read program and when you write your own programs for examplethe following three programs are i...
6,460
variablesexpressionsand statements what is happening herewhich of the tokens (forwordinetc are reserved words and which are just variable namesdoes python understand at fundamental level the notion of wordsbeginning programmers have trouble separating what parts of the code must be the same as this example and what par...
6,461
for syntax errorsthe error messages don' help much the most common messages are syntaxerrorinvalid syntax and syntaxerrorinvalid tokenneither of which is very informative the runtime error you are most likely to make is "use before def;that istrying to use variable before you have assigned value this can happen if you ...
6,462
variablesexpressionsand statements string type that represents sequences of characters type category of values the types we have seen so far are integers (type int)floating-point numbers (type float)and strings (type strvalue one of the basic units of datalike number or stringthat program manipulates variable name that...
6,463
conditional execution boolean expressions boolean expression is an expression that is either true or false the following examples use the operator ==which compares two operands and produces true if they are equal and false otherwise = true = false true and false are special values that belong to the class boolthey are ...
6,464
conditional execution logical operators there are three logical operatorsandorand not the semantics (meaningof these operators is similar to their meaning in english for examplex and is true only if is greater than and less than % = or % = is true if either of the conditions is truethat isif the number is divisible by ...
6,465
if the logical condition is truethen the indented statement gets executed if the logical condition is falsethe indented statement is skipped if statements have the same structure as function definitions or for loops the statement consists of header line that ends with the colon character (:followed by an indented block...
6,466
conditional execution if % = print(' is even'else print(' is odd'if the remainder when is divided by is then we know that is evenand the program displays message to that effect if the condition is falsethe second set of statements is executed no yes % = print(' is odd'print(' is even'figure if-then-else logic since the...
6,467
< > !!print('less'print ('greater'print('equal'figure if-then-elseif logic each condition is checked in order if the first is falsethe next is checkedand so on if one of them is truethe corresponding branch executesand the statement ends even if more than one condition is trueonly the first true branch executes nested ...
6,468
conditional execution yes no = yes no < print('equal'print('less'print''greater'figure nested if statements if and print(' is positive single-digit number ' catching exceptions using try and except earlier we saw code segment where we used the input and int functions to read and parse an integer number entered by the u...
6,469
if we execute this code and give it invalid inputit simply fails with an unfriendly error messagepython fahren py enter fahrenheit temperature: python fahren py enter fahrenheit temperature:fred traceback (most recent call last)file "fahren py"line in fahr float(inpvalueerrorcould not convert string to float'fredthere ...
6,470
conditional execution short-circuit evaluation of logical expressions when python is processing logical expression such as > and ( / it evaluates the expression from left to right because of the definition of andif is less than the expression > is false and so the whole expression is false regardless of whether ( / eva...
6,471
traceback (most recent call last)file ""line in zerodivisionerrordivision by zero in the first logical expressionx > is false so the evaluation stops at the and in the second logical expressionx > is true but ! is false so we never reach ( /yin the third logical expressionthe ! is after the ( /ycalculation so the expre...
6,472
conditional execution branch one of the alternative sequences of statements in conditional statement chained conditional conditional statement with series of alternative branches comparison operator one of the operators that compares its operands==!=>=and <conditional statement statement that controls the flow of execu...
6,473
score > > > > grade enter score enter scoreperfect bad score enter score bad score enter score enter score run the program repeatedly as shown above to test the various different values for input
6,474
conditional execution
6,475
functions function calls in the context of programminga function is named sequence of statements that performs computation when you define functionyou specify the name and the sequence of statements lateryou can "callthe function by name we have already seen one example of function calltype( the name of the function is...
6,476
functions the max function tells us the "largest characterin the string (which turns out to be the letter " "and the min function shows us the smallest character (which turns out to be spaceanother very common built-in function is the len function which tells us how many items are in its argument if the argument to len...
6,477
math functions python has math module that provides most of the familiar mathematical functions before we can use the modulewe have to import itimport math this statement creates module object named math if you print the module objectyou get some information about itprint(maththe module object contains the functions an...
6,478
functions random numbers given the same inputsmost computer programs generate the same outputs every timeso they are said to be deterministic determinism is usually good thingsince we expect the same calculation to yield the same result for some applicationsthoughwe want the computer to be unpredictable games are an ob...
6,479
to choose an element from sequence at randomyou can use choicet [ random choice( random choice( the random module also provides functions to generate random values from continuous distributions including gaussianexponentialgammaand few more adding new functions so farwe have only been using the functions that come with...
6,480
functions print(print_lyricsprint(type(print_lyrics)the value of print_lyrics is function objectwhich has type "functionthe syntax for calling the new function is the same as for built-in functionsprint_lyrics( ' lumberjackand ' okay sleep all night and work all day once you have defined functionyou can use it inside a...
6,481
this program contains two function definitionsprint_lyrics and repeat_lyrics function definitions get executed just like other statementsbut the effect is to create function objects the statements inside the function do not get executed until the function is calledand the function definition generates no output as you ...
6,482
functions inside the functionthe arguments are assigned to variables called parameters here is an example of user-defined function that takes an argumentdef print_twice(bruce)print(bruceprint(brucethis function assigns the argument to parameter named bruce when the function is calledit prints the value of the parameter...
6,483
fruitful functions and void functions some of the functions we are usingsuch as the math functionsyield resultsfor lack of better namei call them fruitful functions other functionslike print_twiceperform an action but don' return value they are called void functions when you call fruitful functionyou almost always want...
6,484
functions def addtwo(ab)added return added addtwo( print(xcodewhen this script executesthe print statement will print out " because the addtwo function was called with and as arguments within the functionthe parameters and were and respectively the function computed the sum of the two numbers and placed it in the local...
6,485
alsodon' forget to save your program before you run it some development environments do this automaticallybut some don' in that casethe program you are looking at in the text editor is not the same as the program you are running debugging can take long time if you keep running the same incorrect program over and overma...
6,486
functions exercises exercise what is the purpose of the "defkeyword in pythonait is slang that means "the following code is really coolbit indicates the start of function cit indicates that the following indented section of code is to be stored for later db and are both true enone of the above exercise what will the fo...
6,487
enter score bad score enter score enter score run the program repeatedly to test the various different values for input
6,488
functions
6,489
iteration updating variables common pattern in assignment statements is an assignment statement that updates variablewhere the new value of the variable depends on the old this means "get the current value of xadd and then update with the new value if you try to update variable that doesn' existyou get an errorbecause ...
6,490
iteration while print(nn print('blastoff!'you can almost read the while statement as if it were english it means"while is greater than display the value of and then reduce the value of by when you get to exit the while statement and display the word blastoff!more formallyhere is the flow of execution for while statemen...
6,491
if you make the mistake and run this codeyou will learn quickly how to stop runaway python process on your system or find where the power-off button is on your computer this program will run forever or until your battery runs out because the logical expression at the top of the loop is always true by virtue of the fact...
6,492
iteration while trueline input(''if line[ ='#'continue if line ='done'break print(lineprint('done!'codehere is sample run of this new program with continue added hello there hello there don' print this print thisprint thisdone doneall the lines are printed except the one that starts with the hash sign because when the ...
6,493
happy new yearjoseph happy new yearglenn happy new yearsally donetranslating this for loop to english is not as direct as the whilebut if you think of friends as setit goes like this"run the statements in the body of the for loop once for each friend in the set named friends looking at the for loopfor and in are reserv...
6,494
iteration we set the variable count to zero before the loop startsthen we write for loop to run through the list of numbers our iteration variable is named itervar and while we do not use itervar in the loopit does control the loop and cause the loop body to be executed once for each of the values in the list in the bo...
6,495
loop loop loop loop loop largest the variable largest is best thought of as the "largest value we have seen so farbefore the loopwe set largest to the constant none none is special constant value which we can store in variable to mark the variable as "emptybefore the loop startsthe largest value we have seen so far is ...
6,496
iteration debugging as you start writing bigger programsyou might find yourself spending more time debugging more code means more chances to make an error and more places for bugs to hide one way to cut your debugging time is "debugging by bisection for exampleif there are lines in your program and you check them one a...
6,497
enter number enter number enter numberbad data invalid input enter number enter numberdone exercise write another program that prompts for list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average
6,498
iteration
6,499
strings string is sequence string is sequence of characters you can access the characters one at time with the bracket operatorfruit 'bananaletter fruit[ the second statement extracts the character at index position from the fruit variable and assigns it to the letter variable the expression in brackets is called an in...