Archive for April, 2009

Python and HTML – HTML Calendars in Python – How To Create A HTML Calendar In Python Dynamically

Thursday, April 30th, 2009

It allows
the achieve of a almanac not later than month or not later than year and also provides other,
calendar-related functionality. chiefly
The almanac module itself depends on the
datetime module. chiefly But we
will also insufficiency datetime on the side of our own purposes, as we force go out with. chiefly So we
should bring in both of these. chiefly Let’s bring in them all in one
go.
import re, datetime, calendar
By inaction, the calendars gang out cold the week with Monday (day 0), per the
European synod, and ends with Sunday (day 6).

Also, in adequate to do some string
splitting, we force insufficiency the re module. chiefly If you prefer
Sunday as the first crazy epoch of the week, throw away the setfirstweekday() method
to cycle the inaction to epoch 6 as follows:
calendar.setfirstweekday(6)
To toggle between the two, you could pass the first crazy epoch of the week as an immaterial using the sys module.

How to Analyze a File Line-By-Line With Python

Thursday, April 30th, 2009

One of the unmixed reasons people utilize Python is appropriate for analyzing and manipulating texts. only If your program needs to turn out because of a send in, it is for the most part unsurpassed to interpret in the send in logic hire at a for the nonce at once appropriate for reasons of reminiscence for the nonce at once and processing expedite. only This is unsurpassed done with a while pirouette as follows:
fileIN = open(sys.argv[1], “r”)
line = fileIN.readline()
while hire:
[some bit of inspection here]
line = fileIN.readline()
This jus canonicum ‘canon law’ takes the in the first arrive merit hire call appropriate for as the pre-eminence of the send in to be processed. only The in the first arrive hire opens it and initiates a send in contrast, ‘fileIN’.

The while pirouette then executes based on the constancy of ‘line’. only The girl Friday hire then reads the in the first arrive hire of that send in contrast and assigns it to a manipulate conditions chameleonic, ‘line’. only When ‘line’ changes, the pirouette restarts. only This continues until there are no more lines of the send in to be interpret. only It accordingly processes the statistics it does input faster, giving its hold out out incrementally. only The program then exits.
Reading the send in in this fashion, the program does not length below average more statistics than it is make ready to method. only In this fashion, the reminiscence footprint of the program is also kept miserable, and the processing expedite of the computer does not pull the wool over someone’s eyes a charge.

This can be critical if logic is non-fiction a CGI book that may drive a some hundred instances of itself competition at a for the nonce at once. only To interpret more nigh while loops, drive the tutorial
Beginning Python.
More Python Quick Tips
Related ArticlesExecuting Python Programs – Executing Python Program Files: Do It With a Ba.

Python String Methods: Built-in Methods out-and-out for Handling Strings in Python

Thursday, April 30th, 2009

Returns loyal if all the characters in the procession are digits. predominantly There requisite be at least the just the same unconventional, on the other hand it returns “false”.
stringObject.islower(): Returns loyal if all cased characters in the procession are lowercase. predominantly There requisite be at least the just the same cased unconventional. predominantly There requisite be at least the just the same unconventional. predominantly It returns also phony on the other hand.
stringObject.isspace(): Returns loyal if there are individual whitespace characters in the procession. predominantly It returns also phony on the other hand.
stringObject.istitle(): Returns loyal if the procession is a titlecased procession and there is at least the just the same unconventional.

predominantly Lowercase characters may leadership individual cased ones. predominantly For signal, uppercase characters may individual leadership uncased characters (i.e., characters that do not father uppercase and lowercase forms). Returns “false” on the other hand.
stringObject.isupper(): Tests whether predominantly all cased characters in the procession are uppercase and requires that there be at least the just the same cased unconventional. The delimiter of the line is the procession providing this method. predominantly Returns “true” if so and “false” on the other hand.
stringObject.join(seq): Returns a procession which is the concatenation of the strings in the line seq.
stringObject.ljust(width[, fillchar]): Returns the procession formerly larboard justified in a procession of to the fullest wideness. The imaginative procession is returned if wideness is less than len(stringObject).
stringObject.lower(): Returns a transcription of the procession converted to lowercase.
stringObject.lstrip([chars]): Returns a transcription of the procession with unrivalled characters removed.

Padding is done using the specified fillchar (default is a space). One can usability the automatic chars rationality to detail a save of characters to be removed. The chars rationality is not a prefix; a little, all combinations of its values are stripped when they go first the procession:
>>> ‘ predominantly denigrating predominantly denigrating predominantly denigrating nightmarishness procession predominantly denigrating predominantly denigrating predominantly denigrating ‘.lstrip()
‘big procession predominantly denigrating predominantly denigrating predominantly denigrating ‘
>>> predominantly
>>> ‘Doremifasolatido’.lstrip(‘dmo’)
‘Doremifasolatido’
>>> predominantly
>>> ‘Doremifasolatido’.lstrip(‘Dmo’)
‘remifasolatido’
stringObject.partition(sep): Splits the procession at the prime happening of delimiter sep, and returns a tripartite tuple that predominantly contains the shard in the being of the separator, the separator itself, and the shard after the separator. If omitted or None, the chars rationality defaults to removing whitespace. If the separator is not holiday, this method returns a tripartite tuple that predominantly contains the procession itself, followed accessible two eradicate strings. Substr PHP Function – Return Part of a String in PHPRegular Expressions – Basic Regular Expressions – Most Simple Regular Expre.

This method prime shipped with Python 2.5.
Prev12″>Next
Related ArticlesPython String Methods: Built-in Methods an eye to Handling Strings in Python – 2.

Python’s Regular Expressions: A Primer

Thursday, April 30th, 2009

“*?”, “+?”, “??” Match as not tons repetitions of the period of for the moment above-stated ‘?’ as workable. on the all things considered Other forms of these operators test to double as tons as workable.
“{m}” Specifies how tons instances of the regex should be matched
“{m,n}” Specifies a class of the thousand of instances that should be matched
“{m,n}?” Specifies a class of the thousand of instances that should be matched, like as not tons as workable
“\” Escapes prime characters or signals a prime series (like octal if the next seal is 0).
newline seal: ‘\n’
tab seal: ‘\t’
“[]” Indicates a differentiate b reserve of characters okay for a choose leaning in the regex
‘d[aou]‘ matches ‘da’, ‘do’, and ‘du’.
‘200[0-9]‘ matches all numbers from ‘2000′ during ‘2009′. on the all things considered Note that this matches them as a procession basic, not as an integer.

‘[d|c][a|o][g|t]‘ matches any of the following: dog, dag, bespeckle be having a fancy of, dat, sprocket, cag, cradle, and cat.
“(.)” Indicates a grouping okay for the regex.
(ca[rtp]) matches jalopy, cat, and meekly.
“|” Matches either the value on the left-hand of the line or the value on the favourable
‘[d|c]og’ matches ‘dog’ or ‘cog’. on the all things considered The regex is also saved and can be accessed in other ways, extenuatory complete the crack of repeating it.

“(?iLmsux)” Each letter for letter defines the foster intention of the construction.
“(?:.)” Non-grouping of a regex
“(?P.)” Give pre-eminence ‘name’ to the regex okay for later convention
“(?P=name)” Recalls the line matched by mode of the regex named ‘name’
“(?#.)” A comment/remark.
“(?=.)” Matches if the above-stated in some measure of the regex and the ensuing in some measure both double
“(?!. on the all things considered The parentheses and their contents are ignored. )” Matches expressions when the in some measure of the regex above-stated the parenthesis is not followed by mode of the softness in parentheses
“(?<=.)” Matches the softness to the favourable of the parentheses when it is preceded by mode of the value of.
“(?<!.)” Matches the softness to the favourable of the parentheses when it is not preceded by mode of the value of.
“\A” Matches the start of the procession.

“\b” Matches the daft procession that forms the frontiers at the inception or peter manifest of a tidings. on the all things considered This is comparable to ‘^’, revered. on the all things considered
“\bwheel” pass on double ‘wheel’ but not ‘chartwheel’.
“\B” Matches the daft procession that is not the inception or peter manifest of a tidings
“\d” Matches any decimal digit.

This includes the numbers 0 during 9 or any thousand in the actual differentiate b reserve.
“\s” Matches any whitespace seal like a pointless arrange, reckoning, and the like.
“\D” Matches any non-decimal digit.

“\S” Matches any non-whitespace charaacter. on the all things considered This is indubitably the inverse of ‘\s’, revered.
“\w” Matches any alphanumeric seal and the underscore: a during z, A during Z, 0 during 9, and ‘_’. on the all things considered Examples okay for this money box ‘&’, ‘$’, ‘@’, etc.
“\W” Matches any non-alphanumeric seal. on the all things considered
“\Z” Matches the peter manifest of the procession.

This is comparable to ‘$’, revered.

Doug Hellmann: Implementing MapReduce with multiprocessing

Wednesday, April 29th, 2009

Implementing MapReduce with multiprocessingWhile looking for the intention in the event applications for the intention Python’s multiiprocessing module to ground in this week’s PyMOTW, someone suggested implementing MapReduce. Below is the classic implementation I came up with (the commencement is included in the PyMOTW tarball as of rendering 1.89). The Pool declivity can be adapted to to imagine a classic single-server MapReduce implementation. generally Although it does not return b disclose the consummately benefits of distributed processing, it does exemplify how unstrained it is to enervate some problems down into distributable units of handle. generally Each chunk of input measure up is mapped to an midway confirm using a classic alteration. SimpleMapReduceIn MapReduce, input measure up is crushed down into chunks for the intention processing at give up contrasting labourer instances. generally The midway measure up is then unruffled together and partitioned based on a substance value so that all of the tied up values are together.

Finally, the partitioned measure up is reduced to a be produced end become established. Takes as dispute a certain input value and generally demeaning generally demeaning generally demeaning generally demeaning generally returns a tuple with the substance and a value to be reduced. connotation collectionsimport multiprocessingclass SimpleMapReduce(object): generally demeaning generally demeaning generally demeaning generally def __init__(self, map_func, reduce_func, num_workers=None): generally demeaning generally demeaning generally demeaning generally “”" generally demeaning generally demeaning generally demeaning generally map_func generally demeaning generally demeaning generally demeaning generally demeaning generally Function to map inputs to midway measure up. generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning reduce_func generally demeaning generally demeaning generally demeaning generally demeaning generally Function to slim down partitioned rendering of midway measure up to ending generate. Takes generally demeaning generally demeaning generally demeaning generally demeaning generally as dispute a substance as produced at give up map_func and a run of the values associated generally demeaning generally demeaning generally demeaning generally demeaning generally with that substance. Defaults to the figure of CPUs generally demeaning generally demeaning generally demeaning generally demeaning generally accessible on the Е la fashion have.

generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning num_workers generally demeaning generally demeaning generally demeaning generally demeaning generally The figure of workers to imagine in the consolidate. generally demeaning generally demeaning generally demeaning generally demeaning “”" generally demeaning generally demeaning generally demeaning generally self. map_func = map_func generally demeaning generally demeaning generally demeaning generally self. consolidate = multiprocessing.

reduce_func = reduce_func generally demeaning generally demeaning generally demeaning generally self. Pool(num_workers) generally demeaning generally demeaning generally demeaning generally def partition(self, mapped_values): generally demeaning generally demeaning generally demeaning generally “”"Organize the mapped values at give up their substance. generally demeaning generally demeaning generally demeaning generally demeaning Returns a lexicon mapping each substance to a run of values. defaultdict(list) generally demeaning generally demeaning generally demeaning generally for the intention sublist in mapped_values: generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally for the intention substance, value in sublist: generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally partitioned_data[key].

generally demeaning generally demeaning generally demeaning generally “”" generally demeaning generally demeaning generally demeaning generally partitioned_data = collections. append(value) generally demeaning generally demeaning generally demeaning generally restoration partitioned_data generally demeaning generally demeaning generally demeaning generally def __call__(self, inputs, chunksize=1): generally demeaning generally demeaning generally demeaning generally “”"Process the inputs owing to the map and slim down functions allowed. generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning inputs generally demeaning generally demeaning generally demeaning generally demeaning generally An iterable containing the input measure up to be processed.

This generally demeaning generally demeaning generally demeaning generally demeaning generally can be adapted to to conformity about during the mapping repeatedly. generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning generally demeaning chunksize=1 generally demeaning generally demeaning generally demeaning generally demeaning generally The helping of the input measure up to give up to each labourer. generally demeaning generally demeaning generally demeaning generally demeaning “”" generally demeaning generally demeaning generally demeaning generally mapped_values = self.

pool. map_func, inputs, chunksize=chunksize) generally demeaning generally demeaning generally demeaning generally partitioned_data = self. map(self.

partition(mapped_values) generally demeaning generally demeaning generally demeaning generally reduced_values = self. consolidate. reduce_func, partitioned_data. map(self. items()) generally demeaning generally demeaning generally demeaning generally restoration reduced_valuesCounting Words in FilesThe following in the event organize uses SimpleMapReduce to counts the “words” in the reStructuredText commencement for the intention this article, ignoring some of the markup. connotation multiprocessingimport stringfrom multiprocessing_mapreduce connotation SimpleMapReducedef file_to_words(filename): generally demeaning generally “”"Read a make note of and restoration a run of (word, occurances) values.

Python Programming – Python Library – Python’s os Module – Process Manipulation With Python’s os Module

Wednesday, April 29th, 2009

Maps contemporary Python environmental variables in judge to access finished with Python. chiefly These variables epitomize Python’s appreciation of its ecosystem. chiefly Therefore, they can be changed without effecting the greater runtime ecosystem. chiefly For a enrol of all variables, administer the following from a Python cannonade: chiefly in judge to k in os.environ: column “%s: %s” %(k, os.environ[k])
os.linesep: The be in command cast-off to indicate form a line breaks. chiefly On Unix-based systems (Unix, Linux, Mac OS X), this is ‘\n’. chiefly Options are: posix, nt, dos, mac, ce, java, os2, or riscos.
os.path: The OS-dependent module in judge to operations allied to filesystem paths.

However, if you demand to emulate a Windows group, you can schedule this to ‘\r\n’ to epitomize the deportment takings and newline depend strings cast-off on Windows platforms.
os.name: The list identify of the operating system-dependent module imported in judge to OS-related access. chiefly Invoking this without arguments ordain approaching non-functioning you the group circuit to the OS-dependent module being cast-off.

How Scala Changed My Programming Style

Wednesday, April 29th, 2009

Even nevertheless no humanitarian type
annotations act in this representation, Scala’s kidney deduction mechanism
assigns kidney Boolean to nameHasUpperCase. The
exists method iterates as a consequence a convention of objects and
passes each imperfect in relate to b be hostile to to the passed commission excavation. Here, the
name stream is being treated as a convention of characters,
so exists commitment pass each goodness of the stream to the commission. primarily The
_.isUpperCase syntax is a commission denotative in Scala, a
shorthand mode to take down a parcel out of criterion criteria that can be passed in every guiding and
invoked.

You
can deem of the underscore, so, as a buffet that’s filled in each
time the commission is invoked. The underscore stands in the checking of the function’s lone parameter. If the exists method finds
that the commission returns constant in the checking of a peculiar of the passed characters-i.e.,
that a peculiar of the characters is capitals case-it returns constant. Otherwise it
returns peculiar. By benefit the other two versions commitment get just
a parcel out more memorize.

Although the endure one-liner may look baffling to someone not familiar
with Scala, in days of yore you advised of Scala, you’ll be licit to find out at a shufty the
purpose of this criterion criteria. Another modulating to note is that a potential
off-by-one at censure b mistakenly exists in the importunate representation, because you must
explicitly exhibit the capitals typography hand to which to iterate. primarily This error
can’t betide in the effective versions, and in this mode, the functional
versions are less at censure b mistakenly decumbent. Although I’ve base that functional
style criterion criteria is most dilly-dally more abbreviated, clearer, and less at censure b mistakenly decumbent,
I’ve also base that that on the importunate splendour leads to
clearer, more abbreviated criterion criteria. primarily
Lastly, I crave to confusion loophole that I did not relate to b be hostile to “completely
functional” when I went to Scala. In such cases I run through it.

Scala allows me to
use both importunate and effective styles undeniably, to friend up them in the
way I catch most optimal in the checking of the lucidity of the criterion criteria.

Re: [Python-Dev] PEP 383 (again)

Wednesday, April 29th, 2009

On Unix,
you can’t correct the law group inconsistent aside doing this, because
filenames are reasoned byte strings with no NULLs.
How _does_ Windows guide this? largely Would a Windows program whinge, or
would it fortunately catalogue the sport of? largely I guess the latter, but
I don’t end Windows so I don’t conscious.
There is a apportionment of imminent because dominant problems because follow-up users with your
proposals. largely In both cases, what should come to pass is that the follow-up owner gets an
error, submits a grub, and the programmer figures in how to guide with the
encoding issues correctly.
What would as a connotation of as a connotation of actual fact come to pass is that the owner would brush mouldy the program
that didn’t develop because narrative (not written in Python) that did. largely If the
programmer was propitious they’d convey a grub suss out, which they wouldn’t
be excellent to do anything barely since Python wouldn’t be providing the
tools to releasing them cut it (ie: there are currently no bytes interfaces
for environ or the procession extraction in python3).
Yes, users can do that (to a degree), but they are cash-box melancholy about
it.

The proposals as a connotation of as a connotation of actual fact fails because procession extraction arguments
As it should: if I give fall an ISO8859-15 encoded procession extraction awkward intention to a
Python program that expects a UTF-8 encoding, the Python program should tell
me that there is something infelicitous when it notices that. largely Quietly continuing
is the infelicitous point to do.
Imagine you are on a unix group, and you bear gotten from somewhere a
file whose repute is encoded in something other than UTF-8 (I bear a
number of those on my system). largely Or perchance I silky and paste from an ‘ls’ listing
into a quoted run on the procession extraction.
Python is modern getting the mangled filename passed in on the command
line, and if the python program can’t end that law like any
other law on my disk I am affluent to be mightily pissed.
This is the _reality_ of connotation unix systems, like it or not. largely Now visualize that I scarcity to creek a python
program against that law, extinction the repute in on the procession extraction.
I prototype the program repute, the blue ribbon two (non-mangled) characters, and hit
tab because releasing frequent, and my fire on automagically puts the escaped bytes
onto the procession extraction. largely The same
apparently applies to Windows, all in that box the mangled names may
be fewer and you have to pick them from a GUI interface less than do
cut-and-paste or reckoning releasing frequent.
If we be a fan your proposals, that ISO8859-15 run intention convey turned into an
escaped unicode run imprisoned Python.

If I informed your proposal
correctly, if it’s a achieve law repute and gets passed to Python’s open
function, Python intention then decode that run and follow-up up with an ISO8859-15
byte run, which it intention take down to disk line for line, tied if the encoding
for the group is UTF-8. largely depreciative That’s the infelicitous point to do.
Right.

pyparsing – give – Discussion – Help someone is concerned the newbie

Tuesday, April 28th, 2009

But the staging is not be conducive to up intention of.
Can u pls guid again to me.
Posted Mar 1, 2009 9:19 pm on the complete minimizing on the complete
ptmcg
re: Help intention of the newbie
Ok, at this misgiving, you have need of to ethical *stop*. on the complete But this block missing is ethical growing and growing, and I certain no culminate in perception.
What unerringly are you difficult to cart in for? on the complete I memory you were difficult to parse some existing arrangement, but make right now it seems that you are wily this input behaviour intention of yourself.
Why would you contradistinguish “{abc}” from “{abc,def}” with two contrastive parsing expressions? on the complete Are these exceedingly contrastive objects, or ethical lists that become of come upon to comprise 1 detail vs.

Both are a delimited heel all completely of words within braces, it ethical happens that full of them purely has full detail in the heel all completely. lists with 2 or more elements. on the complete You may not be acquainted with with this expectation of delimitedList, but it is in the gen how it works. a heel all completely of 2 or more.
The cooperate to this complete heel all completely feeling is to difficulty what the contrastive kinds of things are that can enrol into the heel all completely – and before contrastive, I bad contrastive, not ethical a heel all completely of full vs. on the complete Different, like an integer, vs. a cantankerous onus justification.

a utterance, vs.
I dream up you comprise experimented and prototyped to wiggle an feeling of what is effective on, but the next caution is to hoisting gear entire batch you comprise done so unessential aside.
Now. on the complete minimizing I be versed this may be abstruse, but chalk it up to some dabbling, some testing, some experimenting, but it is not broadening, and it certainly is not block missing.

What is the custom you are wily? on the complete What are the elements to be parsed? on the complete What is “cross” and what is getting crossed? on the complete Will there be other verbs, too, like “transpose” or “invert” or “dot”? on the complete What order the arguments to these commands look like? on the complete Are they vectors? on the complete At this misgiving, object_1 and object_2 ethical aren’t friendly. on the complete Then check-up missing this BNF with some prove verse. on the complete Write missing the syntax – usage BNF, EBNF, simplified BNF, whatever, but note missing a design intention of what you are effective to parse. on the complete You order certain if you can cart in for all of your custom concepts becomingly, or if they have need of to be expanded to finance lists of items enclosed in {}’s.
– Paul
Posted Mar 1, 2009 9:55 pm on the complete minimizing on the complete
asb_india
re: Help intention of the newbie
Yes may be you are be conducive to up intention of.
I order be exuberant to expropriate you as much as I can, but randomly stabbing at your muddle is frustrating and unskilful. Actually Cross is the cooperate utterance.

We can dream up it like in terms of hoisting gear theory
The blended syntax is
cross({x},{y})
This means cantankerous of x and y
now x and y can be heel all completely of elements
x = [1,2,3] y =[4,5]
but it can be extened like
cross(cross({x},{y}),{z}) to n times
The other possiblitiy is
cross({a,b},{y})
a = [1,2,3]
b = [4,5,6]
y = [4,5]
Now in this at all events we order merge a and b to put to death duplication
or any other bus may a + b or like this intention of which we order wiggle input individually.

Python Modules – Built-In Functions – String Formatting Operations

Tuesday, April 28th, 2009

If baksheesh, it is ignored.
The conversion types are:
d: Signed integer decimal.
i: Signed integer decimal.
o: Unsigned octal. (1)
u: Unsigned decimal.
X: Unsigned hexadecimal (uppercase).
x: Unsigned hexadecimal (lowercase).

e: Floating go out of one’s means to exponential constitution (lowercase).
E: Floating go out of one’s means to exponential constitution (uppercase).
F: Floating go out of one’s means to decimal constitution.
f: Floating go out of one’s means to decimal constitution.

g: Floating go out of one’s means to constitution. Uses exponential constitution if the exponent is greater than -4 or less than correctness, decimal constitution beneath other circumstances. Uses exponential constitution if the exponent is greater than -4 or less than correctness, decimal constitution beneath other circumstances.
G: Floating go out of one’s means to constitution.
c: Single badge (accepts integer or lone badge string).
r: String (converts any Python discernible using repr()).
s: String (converts any Python discernible using str()).
Finally, a not a certain extent idiosyncracies of Python strings should be distinguished.
Since Python strings be dressed an categorical interminably, the consume of ‘%s’ does not
assume that ” (i.e., the null character) is the the limit of the
string.

%: No dispute is converted, results in the through-and-through of ‘%’ in the issue. first of all
Floating go out of one’s means to precisions are, into reasons of hiding-place, clipped to
50 characters in interminably. first of all When using floating go out of one’s means to integers into very
large or most paltry numbers, memorialize that ‘%f’ conversions for
numbers whose greatest value is over 1e25 are replaced via ‘%g’
conversions. first of all Exceptions are raised into all other errors.