<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Silveira Neto &#187; Python</title>
	<atom:link href="http://silveiraneto.net/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://silveiraneto.net</link>
	<description></description>
	<lastBuildDate>Fri, 09 Mar 2012 04:13:27 +0000</lastBuildDate>
	<language>pt-br</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Substitutions in a phylogenetic tree file</title>
		<link>http://silveiraneto.net/2012/03/08/substitutions-in-a-phylogenetic-tree-file/</link>
		<comments>http://silveiraneto.net/2012/03/08/substitutions-in-a-phylogenetic-tree-file/#comments</comments>
		<pubDate>Fri, 09 Mar 2012 02:52:49 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[newick tree]]></category>
		<category><![CDATA[phylogenetic]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[source code]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=4073</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2012/03/08/substitutions-in-a-phylogenetic-tree-file/" title="Substitutions in a phylogenetic tree file"></a>The newick tree The Newick tree format is a way of representing a graph trees with edge lengths using parentheses and commas. A newick tree example: (((Espresso:2,(Milk Foam:2,Espresso Macchiato:5,((Steamed Milk:2,Cappucino:2,(Whipped Cream:1,Chocolate Syrup:1,Cafe Mocha:3):5):5,Flat White:2):5):5):1,Coffee arabica:0.1,(Columbian:1.5,((Medium Roast:1,Viennese Roast:3,American Roast:5,Instant Coffee:9):2,Heavy Roast:0.1,French &#8230;<p class="read-more"><a href="http://silveiraneto.net/2012/03/08/substitutions-in-a-phylogenetic-tree-file/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2012/03/08/substitutions-in-a-phylogenetic-tree-file/" title="Substitutions in a phylogenetic tree file"></a><p><a href="http://www.flickr.com/photos/silveiraneto/4119937748/"><img class="size-full wp-image-4077 alignnone" title="orange fish aquarium photo by myself (Silveira Neto)" src="http://silveiraneto.net/wp-content/uploads/2012/03/orange_fish_aquarium_silveira_neto.jpg" alt="" width="640" height="480" /></a></p>
<p><strong>The newick tree</strong></p>
<p>The <a title="The Newick tree format" href="http://evolution.genetics.washington.edu/phylip/newicktree.html">Newick tree format</a> is a way of representing a graph trees with edge lengths using parentheses and commas.</p>
<p>A newick tree example:</p>
<blockquote><p>(((Espresso:2,(Milk Foam:2,Espresso Macchiato:5,((Steamed Milk:2,Cappucino:2,(Whipped Cream:1,Chocolate Syrup:1,Cafe Mocha:3):5):5,Flat White:2):5):5):1,Coffee arabica:0.1,(Columbian:1.5,((Medium Roast:1,Viennese Roast:3,American Roast:5,Instant Coffee:9):2,Heavy Roast:0.1,French Roast:0.2,European Roast:1):5,Brazilian:0.1):1):1,Americano:10,Water:1);</p></blockquote>
<p>A graphical representation for the newick tree above (using the <a title="jsphylosvg library newick tree" href="http://www.jsphylosvg.com/">http://www.jsphylosvg.com/</a> library):</p>
<p><img class="aligncenter size-full wp-image-4074" title="tree representation" src="http://silveiraneto.net/wp-content/uploads/2012/03/tree_representation.png" alt="" width="400" height="509" /></p>
<p>The Newick format is commonly used for store <a title="Evolutionary trees" href="http://evolution.berkeley.edu/evolibrary/article/phylogenetics_01">phylogenetic trees</a>.</p>
<p><strong>The problem</strong></p>
<p>A phylogenetic tree can be highly branched and dense and even using proper visualization software can be difficult to analyse it. Additionally, as a tree are produced by a chain of different software with data from the laboratory, the label for each leaf/node can be something not meaningful for a human reader.</p>
<p>For this particular problem, an example of a node label could be SXS<em>_3014_Albula_vulpes_id_30</em>.</p>
<p>There was a spreadsheet with more meaningful information where a node label could be used as a <a title="overview of the Structured Query Language" href="http://www.xcdsql.org/Summary%20of%20SQL.html#chapter-Table%20constraints">primary key</a>. Example for the node above:</p>
<table>
<tbody>
<tr>
<th>Taxon Order</th>
<th>Family</th>
<th>Genus</th>
<th>Species</th>
<th>ID</th>
</tr>
<tr>
<td>Albuliformes</td>
<td>Albulidae</td>
<td>Albula</td>
<td>vulpes</td>
<td><em>SXS_3014_Albula_vulpes_id_30</em></td>
</tr>
</tbody>
</table>
<p>The problem consists in using the tree and the spreadsheet to produce a new tree with the same structure, where each node have a more meaningful label.</p>
<p><strong>The approach</strong></p>
<p>The new tree can be mounted by substituting each label of the initial tree with the respective information from the spreadsheet. A script can be used to automate this process.</p>
<p><strong>The solution</strong></p>
<p>After converting the spreadsheet to a <a title="Y. Shafranovich" href="http://tools.ietf.org/html/rfc4180">CSV file</a> that could be more easily handled by a <a title="Python" href="http://docs.python.org/library/csv.html">CSV Python library</a> the problem is reduced to a file handling and string substitution. Fortunately, due the simplicity of the Newick format and its limited vocabulary, a tree parser is not necessary.</p>
<p><script src="https://gist.github.com/2004714.js?file=tree_substitution.py"></script></p>
<p><small><a href="https://gist.github.com/2004714" title="Github Gist" target="_blank">Source-code at Github</a>.</small></p>
<p><strong>Difficulties found</strong></p>
<p>The spreadsheet was originally in a Microsoft Office Excel 2007 (.xlsx) and the conversion to CSV provided by Excel was not good and there was no configuration option available. Finally, the conversion provided by <a href="http://www.libreoffice.org/" title="LibreOffice">LibreOffice Productivity Suite</a> was more configurable and was easier to read by the CSV library.</p>
<p>In the script, the <a href="http://docs.python.org/library/csv.html#csv.DictReader" title="Python DictReader Documentation">DictReader class</a> showed in the the long-term much more reliable and tolerant to changes in the spreadsheet as long the names of the columns remain the same.</p>
<p><small>P.S. due to the nature of the original sources for the tree and spreadsheet I don&#8217;t have the authorization for public publishing their complete and original content. The artificial data displayed here is merely illustrative.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2012/03/08/substitutions-in-a-phylogenetic-tree-file/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>GenBank renaming</title>
		<link>http://silveiraneto.net/2012/02/20/genbank-renaming/</link>
		<comments>http://silveiraneto.net/2012/02/20/genbank-renaming/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 06:08:30 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[Bioinform]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[biopython]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[setuptools]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=4023</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2012/02/20/genbank-renaming/" title="GenBank renaming"></a>DNA inspired sculpture by Charles Jencks. Creative Commons photo by Maria Keays. What is GenBank? The GenBank sequence database is a widely used collection of nucleotide sequences and their protein translations. A GenBank sequence record file typically has a .gbk &#8230;<p class="read-more"><a href="http://silveiraneto.net/2012/02/20/genbank-renaming/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2012/02/20/genbank-renaming/" title="GenBank renaming"></a><p><img class="size-full wp-image-4024" title="DNA sculpture at Centre for Life by Maria Keays on Flickr. Sculpture by  Charles Jencks" src="http://silveiraneto.net/wp-content/uploads/2012/02/DNA-sculpture-at-Centre-for-Life-by-Maria-Keays-on-Flickr.jpg" alt="http://www.flickr.com/photos/maria_keays/1251843227/" width="640" height="480" /><br />
<small>DNA inspired sculpture by Charles Jencks. Creative Commons photo by <a title="Flickr" href="http://www.flickr.com/photos/maria_keays/1251843227/">Maria Keays</a>.</small></p>
<p><strong>What is GenBank?</strong></p>
<p>The <a href="http://www.ncbi.nlm.nih.gov/genbank/">GenBank</a> sequence database is a widely used collection of nucleotide sequences and their protein translations. A GenBank sequence record file typically has a .gbk or .gb extension and is filled with plain text characters. A example of GenBank file can be found <a href="http://silveiraneto.net/downloads/sequence.gb">here</a>.</p>
<p><strong>Filename problem</strong></p>
<p>Although there are several metadata are available inside a GenBank record the name of the file are not always in accordance with the content of the file. This is potentially a source of confusion to organize files and requires an additional effort to rename the files according to their content.</p>
<p><strong>Approach using Biopython</strong></p>
<p>The Biopython project is a mature open source international collaboration of volunteer developers, providing Python libraries for a wide range of bioinformatics problems. Among other tools, Biopython includes modules for reading and writing different sequence file formats including the GenBank&#8217;s record files.</p>
<p>Despite the fact that is possible to write a parser for GenBank&#8217; files it would represent a redundant effort to develop and maintain such tool. Biopython can be delegated to perform parsing and focus the programming on renaming mechanism.</p>
<p><strong>Biopython installation on Linux (Ubuntu 11.10) or Apple OS X (Lion)</strong></p>
<p>For both Ubuntu 11.10 and OS X Lion, a modern version of Python already comes out of the box.</p>
<p>For Linux you just need to install the Biopython package. One method to install Biopython in a APT ready distribution as Ubuntu 11.10 (Oneiric Ocelot) is:</p>
<blockquote><p># apt-get install python-biopython</p></blockquote>
<p>For an Apple OS X (Lion) you can install Biopython using <em>easy_install</em>, a popular package manager for the Python. <em>Easy_install</em> is bundled with <em>Setuptools</em>, a set of tools for Python.</p>
<p>To install the <em>Setuptools</em> <a href="http://pypi.python.org/pypi/setuptools#files">download the .egg file</a> for your python version (probably setuptools-0.6c11-py2.7.egg) and execute it as a Shell Script:</p>
<blockquote><p>sudo sh setuptools-0.6c11-py2.7.egg</p></blockquote>
<p>After this you already have easy_install in place and you can use it to install the Biopython library:</p>
<blockquote><p>sudo easy_install -f http://biopython.org/DIST/ biopython</p></blockquote>
<p>For both operational systems you can test if you already have Biopython installed using the Python iterative terminal:</p>
<blockquote><p>$ python<br />
Python 2.7.2+ (default, Oct 4 2011, 20:03:08)<br />
[GCC 4.6.1] on linux2<br />
Type &#8220;help&#8221;, &#8220;copyright&#8221;, &#8220;credits&#8221; or &#8220;license&#8221; for more information.<br />
&gt;&gt;&gt; import Bio<br />
&gt;&gt;&gt; Bio.__version__<br />
&#8217;1.57&#8242;<br />
&gt;&gt;&gt;</p></blockquote>
<p><strong>Automatic rename example through scripting</strong></p>
<p>Below the <a href="https://gist.github.com/1859976" title="at Github">Python source-code for a simple use of using Biopython to rename a Genbank file</a> to it&#8217;s description after removing commas and spaces.</p>
<p><script src="https://gist.github.com/1859976.js?file=gbkrename.py"></script></p>
<p>Using the the previous example of GenBank file, suppose you have a file called <a href="http://silveiraneto.net/downloads/sequence.gb">sequence.gb</a>. To rename this file to the GenBank description metadata inside it you can use the script.</p>
<blockquote><p>python gbkrename.py sequence.gb</p></blockquote>
<p>And after this it will be called Hippopotamus_amphibius_mitochondrial_DNA_complete_genome.gbk.</p>
<p><strong>Improvements</strong></p>
<p>There is plenty of room for improvement as:</p>
<ul>
<li>Better command line parsing with <a href="http://docs.python.org/library/optparse.html">optparse</a> and parameterization of all possible configuration.</li>
<li>A graphical interface</li>
<li>Handle special cases such multiple sequences in a single GenBank file.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2012/02/20/genbank-renaming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python, flatten a list</title>
		<link>http://silveiraneto.net/2011/10/08/python-flatten-a-list/</link>
		<comments>http://silveiraneto.net/2011/10/08/python-flatten-a-list/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 21:38:07 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[flatten]]></category>
		<category><![CDATA[lists]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3929</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2011/10/08/python-flatten-a-list/" title="Python, flatten a list"></a>Surprisingly python doesn&#8217;t have a shortcut for flatten a list (more generally a list of lists of lists of&#8230;). I made a simple implementation that doesn&#8217;t use recursion and tries to be written clearly. I get a element from a &#8230;<p class="read-more"><a href="http://silveiraneto.net/2011/10/08/python-flatten-a-list/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2011/10/08/python-flatten-a-list/" title="Python, flatten a list"></a><p>Surprisingly python doesn&#8217;t have a shortcut for flatten a list (more generally a list of lists of lists of&#8230;).</p>
<p>I made a simple implementation that doesn&#8217;t use recursion and tries to be written clearly.</p>
<p><script src="https://gist.github.com/1229108.js?file=flatten"></script></p>
<p>I get a element from a &#8220;bad&#8221; list (a list that can have another lists). If the element is not a list we store in our flat list. If the element is still a list we deal with him later. The flat list always have elements that are not a list.<br />
To preserve the original order we reverse the elements at the end.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2011/10/08/python-flatten-a-list/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Contando Algarismos Em Um Intervalo</title>
		<link>http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/</link>
		<comments>http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 23:21:59 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[compreensão de lista]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[programação funcional]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3142</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/" title="Contando Algarismos Em Um Intervalo"></a>Quantos zeros tem entre um e mil? É mais fácil responder perguntas desse tipo escrevendo pequenos programas usando o suporte a programação funcional e compreensão de lista que algumas linguagens como Python oferecem. Para contar os zeros de um número, &#8230;<p class="read-more"><a href="http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/" title="Contando Algarismos Em Um Intervalo"></a><p><strong>Quantos zeros tem entre um e mil?</strong></p>
<p>É mais fácil responder perguntas desse tipo escrevendo pequenos programas usando o suporte a <a href="http://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional">programação funcional</a> e <a href="http://pt.wikipedia.org/wiki/List_comprehension">compreensão de lista</a> que algumas linguagens como Python oferecem.</p>
<p>Para contar os zeros de um número, transformamos ele em uma string e contamos quantas substrings &#8217;0&#8242; ele contém. Por exemplo o 800:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">800</span><span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># 2</span></pre></div></div>

<p>Para gerar uma lista ordenada com os elementos do intervalo entre um e mil, inclusive os valores um e mil:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># [1, 2, ... , 999, 1000]</span></pre></div></div>

<p>Pegamos esse intervalo  e geramos uma outra lista onde cada elemento é a contagem dos zeros do número do intervalo.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: black;">&#91;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
<span style="color: #808080; font-style: italic;"># [0, 0, ... , 0, 3]</span></pre></div></div>

<p>Por exemplo, 1 não tem nenhum zero. Dois também não. 999 também não. 1000 tem três.</p>
<p>Somamos todos os elementos da lista temos o número de algarismos zero entre um e mil.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #008000;">sum</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x<span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>E a resposta é 192.</p>
<p>O mesmo poderia ser obtido contando quantos zeros há na representação de string da lista do intervalo.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #008000;">str</span><span style="color: black;">&#40;</span><span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1001</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">count</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'0'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Mas essa abordagem apesar de menor é menos geral se você quiser modifica-la para contagens mais complexas.</p>
<p>A diferença do range pro xrange é que o range constrói a lista real do intervalo real em memória e o xrange uma representação da lista do intervalo. Em geral mas não sempre, a performasse do xrange é melhor.</p>
<p>De toda forma, em ambos os casos, o resultado é o mesmo.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2010/01/29/contando-algarismos-em-um-intervalo/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Easily Sortable Date and Time Representation</title>
		<link>http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/</link>
		<comments>http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 01:55:26 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[ISO 8601]]></category>
		<category><![CDATA[Jochen Voss]]></category>
		<category><![CDATA[Markus Kuhn]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[representation]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3130</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/" title="Easily Sortable Date and Time Representation"></a>I was looking for a date and time representation useful for registering stock quotes in a simple plain file. I found that the standard ISO 8601 is just the answer for this, it&#8217;s called &#8220;Data elements and interchange formats — Information &#8230;<p class="read-more"><a href="http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/" title="Easily Sortable Date and Time Representation"></a><p>I was looking for a date and time representation useful for registering stock quotes in a simple plain file.</p>
<p>I found that the standard <a title="Wikipedia on ISO 8601" href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> is just the answer for this, it&#8217;s called &#8220;Data elements and interchange formats — Information interchange — Representation of dates and times&#8221;. Here is a example:</p>
<blockquote><p>2010-01-20 22:14:38</p></blockquote>
<p>There&#8217;s this good article from <a title="A summary of the international standard date and time notation" href="http://www.cl.cam.ac.uk/~mgk25/iso-time.html">Markus Kuhn, &#8220;A summary of the international standard date and time notation&#8221;</a>. <strong>This notation allow us to using simple lexicographical order the events.</strong></p>
<p>Some examples of how to do this in Python (thanks for the <a href="http://seehuhn.de/pages/pdate">Jochen Voss article &#8220;Date and Time Representation in Python&#8221;</a>) The first for displaying the current date and time:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">time</span> <span style="color: #ff7700;font-weight:bold;">import</span> strftime
<span style="color: #ff7700;font-weight:bold;">print</span> strftime<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%Y-%m-%d %H:%M:%S&quot;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># 2010-01-20 22:34:22</span></pre></div></div>

<p>Another possibility is using strftime from datetime object.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">datetime</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">datetime</span>
now = <span style="color: #dc143c;">datetime</span>.<span style="color: #dc143c;">datetime</span>.<span style="color: black;">now</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> now.<span style="color: black;">strftime</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%Y-%m-%d %H:%M:%S&quot;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># 2010-01-20 22:12:31</span></pre></div></div>

<p>Is that. Using this notation in the begging of each line is easy to sort them in any language or using the unix <a href="http://en.wikipedia.org/wiki/Sort_%28Unix%29">sort</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2010/01/20/easily-sortable-date-and-time-representation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extração de Dados e Fundos de Investimento do Banco do Brasil</title>
		<link>http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/</link>
		<comments>http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 00:02:42 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[ações]]></category>
		<category><![CDATA[aplicações]]></category>
		<category><![CDATA[Banco do Brasil]]></category>
		<category><![CDATA[bolsa de valores]]></category>
		<category><![CDATA[CRON]]></category>
		<category><![CDATA[Data Mining]]></category>
		<category><![CDATA[fundo de investimento]]></category>
		<category><![CDATA[fundos]]></category>
		<category><![CDATA[fundos de investimento]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Mineração de Dados]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[screen scraping]]></category>
		<category><![CDATA[Web Harvest]]></category>
		<category><![CDATA[web scraping]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[yaml]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3112</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/" title="Extração de Dados e Fundos de Investimento do Banco do Brasil"></a>Eu não achei onde coletar os dados diários de rentabilidade dos fundos de investimento do Banco do Brasil em formato bem estruturado. Num mundo ideal as coisas seriam assim, você faria uma requisição numa url como esta: http://bb.com.br/apps/rentabilidade?fundo=Siderurgia&#38;saida=xml E ele &#8230;<p class="read-more"><a href="http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/" title="Extração de Dados e Fundos de Investimento do Banco do Brasil"></a><p style="text-align: center;"><img class="size-full wp-image-3118 aligncenter" title="unicornio" src="http://silveiraneto.net/wp-content/uploads/2010/01/unicornio1.jpg" alt="" width="400" height="440" /></p>
<p>Eu não achei onde coletar os dados diários de rentabilidade dos <a title="Fundos de Investimento do Banco do Brasil" href="http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01">fundos de investimento do Banco do Brasil</a> em formato bem estruturado.</p>
<p>Num mundo ideal as coisas seriam assim, você faria uma requisição numa url como esta:</p>
<blockquote><p>http://bb.com.br/apps/rentabilidade?fundo=Siderurgia&amp;saida=xml</p></blockquote>
<p>E ele cuspiria um XML com as informações da rentabilidade diária desse fundo, isso se eu não especificasse através de outro parâmetro qual a data ou intervalo de datas desejado ou outro tipo de dados para saída como YAML ou JSON. Mas por enquanto não temos isso, nem unicórnios, então temos de fazer as coisas do jeito mais difícil, que é puxando os <a title="tabela dos fundos de investimento" href="http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01">dados feitos para humanos</a> e escrevendo um programa pra extrair à força os dados que desejamos e quem sabe usar eles para algum uso relacionado a <a href="http://pt.wikipedia.org/wiki/Minera%C3%A7%C3%A3o_de_dados">mineração de dados</a>.</p>
<p style="text-align: center;"><img class="size-full wp-image-3113 aligncenter" title="bb fundos de investimento" src="http://silveiraneto.net/wp-content/uploads/2010/01/bb_fundos_de_investimento.png" alt="" width="494" height="318" /></p>
<p>A primeira abordagem que eu tentei foi a de criar <a href="http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/">um desses pequenos parsers XML que eu já mostrei como fazer antes</a>, mas o código fonte desse documento se mostrou muito incompatível com o XML que o parser estava disposto a trabalhar. A solução alternativa foi tratar o documento linha a linha.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># abrimos o documento referenciado pela url</span>
url = <span style="color: #483d8b;">'http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01'</span>
documento = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># fundo de investimento que me interessa</span>
fundo = <span style="color: #483d8b;">'small caps'</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estados</span>
INICIO = <span style="color: #ff4500;">0</span>
ACHOU_FUNDO = <span style="color: #ff4500;">1</span>
FIM = <span style="color: #ff4500;">2</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estado inicial</span>
estado = INICIO
&nbsp;
<span style="color: #808080; font-style: italic;"># vamos analisar linha a linha do fluxo do documento</span>
<span style="color: #ff7700;font-weight:bold;">for</span> linha <span style="color: #ff7700;font-weight:bold;">in</span> documento:
	<span style="color: #808080; font-style: italic;"># simplificamos, tudo pra minusculas</span>
	linha = linha.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># no inicio, procura uma linha que tenha o fundo</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> estado == INICIO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span>fundo<span style="color: black;">&#41;</span> <span style="color: #66cc66;">!</span>= -<span style="color: #ff4500;">1</span>:
		estado = ACHOU_FUNDO
&nbsp;
	<span style="color: #808080; font-style: italic;"># depois, procuramos o proximo inicio de tabela html.</span>
	<span style="color: #808080; font-style: italic;"># dessa linha, pegamos o que vem depois do primeiro &amp;gt;</span>
	<span style="color: #808080; font-style: italic;"># e entao o que vem antes do primeiro &amp;lt;</span>
	<span style="color: #808080; font-style: italic;"># e trocamos a virgula por ponto.</span>
	<span style="color: #ff7700;font-weight:bold;">elif</span> estado == ACHOU_FUNDO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&gt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&lt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>.<span style="color: black;">replace</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">','</span>,<span style="color: #483d8b;">'.'</span><span style="color: black;">&#41;</span>
		estado = FIM</pre></div></div>

<p>E para usar:</p>
<blockquote><p>$ python rendimento_small_caps.py<br />
0.881</p></blockquote>
<p>Geralmente estamos mais interessados em saber o valor da cota daquele fundo, daí podemos calcular o rendimento total sabendo a cota que compramos a ação inicialmente. Nesse caso o dado está na 11º coluna.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urllib</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># abrimos o documento referenciado pela url</span>
url = <span style="color: #483d8b;">'http://www21.bb.com.br/portalbb/rentabilidade/index.jsp?tipo=01'</span>
documento = <span style="color: #dc143c;">urllib</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>url<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># fundo de investimento que me interessa</span>
fundo = <span style="color: #483d8b;">'small caps'</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estados</span>
INICIO = <span style="color: #ff4500;">0</span>
ACHOU_FUNDO = <span style="color: #ff4500;">1</span>
FIM = <span style="color: #ff4500;">2</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># estado inicial</span>
estado = INICIO
coluna = <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># vamos analisar linha a linha do fluxo do documento</span>
<span style="color: #ff7700;font-weight:bold;">for</span> linha <span style="color: #ff7700;font-weight:bold;">in</span> documento:
	<span style="color: #808080; font-style: italic;"># simplificamos, tudo pra minusculas</span>
	linha = linha.<span style="color: black;">lower</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># no inicio, procura uma linha que tenha o fundo</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> estado == INICIO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span>fundo<span style="color: black;">&#41;</span> <span style="color: #66cc66;">!</span>= -<span style="color: #ff4500;">1</span>:
		estado = ACHOU_FUNDO
&nbsp;
	<span style="color: #808080; font-style: italic;"># para cada coluna, conta a coluna, mas nao faz nada</span>
	<span style="color: #ff7700;font-weight:bold;">elif</span> estado == ACHOU_FUNDO <span style="color: #ff7700;font-weight:bold;">and</span> linha.<span style="color: black;">find</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&lt;'</span><span style="color: black;">&#41;</span>:
		coluna += <span style="color: #ff4500;">1</span>
&nbsp;
	<span style="color: #808080; font-style: italic;"># quando chegar na coluna onze, retira o conteudo entre os sinais &amp;gt; e &amp;lt;</span>
	<span style="color: #808080; font-style: italic;"># e troca virgula por ponto, transforma em float e joga na tela</span>
	<span style="color: #ff7700;font-weight:bold;">if</span> estado==ACHOU_FUNDO <span style="color: #ff7700;font-weight:bold;">and</span> coluna == <span style="color: #ff4500;">11</span>:
		<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">float</span><span style="color: black;">&#40;</span>linha.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&gt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'&lt;'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>.<span style="color: black;">replace</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">','</span>,<span style="color: #483d8b;">'.'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		estado = FIM</pre></div></div>

<blockquote><p>$ python cota_small_caps.py<br />
6.156906634</p></blockquote>
<p>Essa é uma abordagem que eu não gosto nem recomendo porque ela é muito frágil e está extremamente acoplada a formatação de dados para humanos. Esta formatação está interessada no saída gráfica que o usuário vai obter e não em facilitar a extração (não humana) desses dados. Isso torna a solução muito frágil:</p>
<ul>
<li>Se mudarem os nomes internos dos elementos, a solução pode falhar.</li>
<li>Se mudarem a formatação da tabela, a solução pode falhar.</li>
<li>Se mudarem a disposição interna dos elementos html, a solução pode falhar.</li>
<li>Se mudarem a url do documento, a solução vai falhar.</li>
<li>Se o documento não puder mais ser tratado linha a linha, a solução vai falhar feio.</li>
</ul>
<p>É provável que quando você estiver lendo isso ela nem funcione mais do jeito que está descrita aqui.</p>
<p>Por outro lado, a solução funciona e nesse caso é o que me interessa. Quando ela quebrar, se ainda for do meu interesse eu posso rapidamente conserta-la e os dados já coletados no passado continuam válidos.</p>
<p>Isso somado  a uma programa como o Cron pode se tornar uma ferramenta realmente poderosa.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2010/01/11/extracao-de-dados-e-fundos-de-investimento-do-banco-do-brasil/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python Fast XML Parsing</title>
		<link>http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/</link>
		<comments>http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/#comments</comments>
		<pubDate>Fri, 25 Dec 2009 18:04:50 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[dtd]]></category>
		<category><![CDATA[expat]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[sax]]></category>
		<category><![CDATA[schema]]></category>
		<category><![CDATA[urllib]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3081</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/" title="Python Fast XML Parsing"></a>Here is a useful tip on Python XML decoding. I was extending xml.sax.ContentHandler class in a example to decode maps for a Pygame application when my connection went down and I noticed that the program stop working raising a exception &#8230;<p class="read-more"><a href="http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/" title="Python Fast XML Parsing"></a><p style="text-align: center;"><img class="size-full wp-image-3082 aligncenter" title="monty python bunny toy" src="http://silveiraneto.net/wp-content/uploads/2009/12/monty_python_bunny_toy.jpg" alt="" width="175" height="178" /></p>
<p>Here is a useful tip on Python XML decoding.</p>
<p>I was extending <a title="Python Documentation on XML SAX" href="http://docs.python.org/library/xml.sax.html">xml.sax.ContentHandler</a> class in <a title="Tiled TMX Map Loader for Pygame" href="http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/">a example to decode maps for a Pygame application</a> when my connection went down and I noticed that the program stop working raising a exception regarded a call to <a title="Python Documentation on urllib" href="http://docs.python.org/library/urllib.html">urlib</a> (a module for retrieve resources by url). I noticed that the module was getting the remote <a title="Wikipedia on Document Type Definition" href="http://en.wikipedia.org/wiki/Document_Type_Definition">DTD schema</a> to validate the XML.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE map SYSTEM &quot;http://mapeditor.org/dtd/1.0/map.dtd&quot;&gt;</span></pre></div></div>

<p>This is not a requirement for my applications and it&#8217;s a huge performance overhead when works (almost 1 second for each map loaded) and when the applications is running in a environment without Internet it just waits for almost a minute and then fail with the remain decoding. A dirty workaround is open the XML file and get rid of the line containing the DTD reference.</p>
<p>But the correct way to programming XML decoding when we are not concerned on validate a XML schema is just the <a href="http://docs.python.org/library/pyexpat.html">xml.parsers.expat</a>. Instead of using a interface you just have to set some callback functions with the behaviors we want. This is a example from the documentation:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">xml</span>.<span style="color: black;">parsers</span>.<span style="color: black;">expat</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># 3 handler functions</span>
<span style="color: #ff7700;font-weight:bold;">def</span> start_element<span style="color: black;">&#40;</span>name, attrs<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Start element:'</span>, name, attrs
<span style="color: #ff7700;font-weight:bold;">def</span> end_element<span style="color: black;">&#40;</span>name<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'End element:'</span>, name
<span style="color: #ff7700;font-weight:bold;">def</span> char_data<span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Character data:'</span>, <span style="color: #dc143c;">repr</span><span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>
&nbsp;
p = <span style="color: #dc143c;">xml</span>.<span style="color: black;">parsers</span>.<span style="color: black;">expat</span>.<span style="color: black;">ParserCreate</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
p.<span style="color: black;">StartElementHandler</span> = start_element
p.<span style="color: black;">EndElementHandler</span> = end_element
p.<span style="color: black;">CharacterDataHandler</span> = char_data
&nbsp;
p.<span style="color: black;">Parse</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;parent id=&quot;top&quot;&gt;&lt;child1 name=&quot;paul&quot;&gt;Text goes here&lt;/child1&gt;
&lt;child2 name=&quot;fred&quot;&gt;More text&lt;/child2&gt;
&lt;/parent&gt;&quot;&quot;&quot;</span>, <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The output:</p>
<pre>
Start element: parent {'id': 'top'}
Start element: child1 {'name': 'paul'}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 {'name': 'fred'}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent
</pre>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/25/python-fast-xml-parsing/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Tiled TMX Map Loader for Pygame</title>
		<link>http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/</link>
		<comments>http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 10:15:48 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Qt]]></category>
		<category><![CDATA[Tiled]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3063</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/" title="Tiled TMX Map Loader for Pygame"></a>I&#8217;m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It&#8217;s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my &#8230;<p class="read-more"><a href="http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/" title="Tiled TMX Map Loader for Pygame"></a><p>I&#8217;m using the <a href="http://mapeditor.org/">Tiled Map Editor</a> for a while, I even wrote <a href="http://silveiraneto.net/2009/01/11/game-map-edition-using-tiled/">that tutorial about it</a>. It&#8217;s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with <a title="pixel art work" href="http://silveiraneto.net/tag/pixelart">my set of free pixelart tiles</a>.</p>
<p><center><a href="../wp-content/uploads/2009/01/map_editor_tiles_tileset_game-deveopment.png"><img title="map editor tiles tileset game deveopment" src="../wp-content/uploads/2009/01/map_editor_tiles_tileset_game-deveopment-500x343.png" alt="map editor tiles tileset game deveopment" width="500" height="343" /></a></center></p>
<p>A map done with Tiled is stored in a file with TMX extension. It&#8217;s just a XML file, easy to understand.</p>
<p>As I&#8217;m creating a map loader for my owns purposes, the procedure I&#8217;m doing here works we need some simplifications. I&#8217;m handling orthogonal maps only. I&#8217;m not supporting tile properties as well. I also don&#8217;t want to handle base64 and zlib encoding in this version, so in the Tiled editor, go at the menu <em>Edit → Preferences</em> and in the <em>Saving</em> tab unmark the options &#8220;Use binary encoding&#8221; and &#8220;Compress Layer Data (gzip)&#8221;, like this:</p>
<p style="text-align: center;"><img class="size-full wp-image-3064 aligncenter" title="Tiled Preferences Window" src="http://silveiraneto.net/wp-content/uploads/2009/12/Tiled_preferences.png" alt="Tiled Preferences Window" width="370" height="309" /></p>
<p>When saving a map it will produce a TMX file like this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #00bbdd;">&lt;!DOCTYPE map SYSTEM &quot;http://mapeditor.org/dtd/1.0/map.dtd&quot;&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;map</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">orientation</span>=<span style="color: #ff0000;">&quot;orthogonal&quot;</span> <span style="color: #000066;">width</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">height</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">tilewidth</span>=<span style="color: #ff0000;">&quot;32&quot;</span> <span style="color: #000066;">tileheight</span>=<span style="color: #ff0000;">&quot;32&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Author&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Silveira Neto&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Year&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;2009&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tileset</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;mytiles&quot;</span> <span style="color: #000066;">firstgid</span>=<span style="color: #ff0000;">&quot;1&quot;</span> <span style="color: #000066;">tilewidth</span>=<span style="color: #ff0000;">&quot;32&quot;</span> <span style="color: #000066;">tileheight</span>=<span style="color: #ff0000;">&quot;32&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;image</span> <span style="color: #000066;">source</span>=<span style="color: #ff0000;">&quot;free_tileset_version_10.png&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tileset<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;layer</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;grass&quot;</span> <span style="color: #000066;">width</span>=<span style="color: #ff0000;">&quot;10&quot;</span> <span style="color: #000066;">height</span>=<span style="color: #ff0000;">&quot;10&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;data<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;261&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;260&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    ...
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;160&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tile</span> <span style="color: #000066;">gid</span>=<span style="color: #ff0000;">&quot;0&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/data<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/layer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>For processing it on Python I&#8217;m using the <a href="http://docs.python.org/whatsnew/2.0.html#sax2-support">event oriented SAX approach for XML</a>. So I create a ContentHandler that handles events the start and end of XML elements. In the first element, map, I know enough to create a <a href="http://www.pygame.org/docs/ref/surface.html">Pygame surface</a> with the correct size. I&#8217;m also storing the map properties so I can use it later for add some logics or effects on the map. After that we create a instance of the Tileset class from where we will get the each tile by an gid number. Each layer has it&#8217;s a bunch of gids in the correct order. So it&#8217;s enough information to mount and draw a map.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Author: Silveira Neto</span>
<span style="color: #808080; font-style: italic;"># License: GPLv3</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>, pygame
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
<span style="color: #ff7700;font-weight:bold;">from</span> pygame <span style="color: #ff7700;font-weight:bold;">import</span> Rect
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">xml</span> <span style="color: #ff7700;font-weight:bold;">import</span> sax
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Tileset:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #008000;">file</span>, tile_width, tile_height<span style="color: black;">&#41;</span>:
        image = pygame.<span style="color: black;">image</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>.<span style="color: black;">convert_alpha</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> image:
            <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Error creating new Tileset: file %s not found&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: #008000;">file</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span> = tile_width
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> = tile_height
        <span style="color: #008000;">self</span>.<span style="color: black;">tiles</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> line <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>image.<span style="color: black;">get_height</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>/<span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">for</span> column <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span>image.<span style="color: black;">get_width</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>/<span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span><span style="color: black;">&#41;</span>:
                pos = Rect<span style="color: black;">&#40;</span>
                        column<span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>,
                        line<span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span>,
                        <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>,
                        <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> <span style="color: black;">&#41;</span>
                <span style="color: #008000;">self</span>.<span style="color: black;">tiles</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>image.<span style="color: black;">subsurface</span><span style="color: black;">&#40;</span>pos<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> get_tile<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, gid<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">tiles</span><span style="color: black;">&#91;</span>gid<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> TMXHandler<span style="color: black;">&#40;</span>sax.<span style="color: black;">ContentHandler</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">width</span> = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">height</span> = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span> = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">columns</span> = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">lines</span>  = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">properties</span> = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">image</span> = <span style="color: #008000;">None</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">tileset</span> = <span style="color: #008000;">None</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> startElement<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name, attrs<span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;"># get most general map informations and create a surface</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> name == <span style="color: #483d8b;">'map'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">columns</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'width'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">lines</span>  = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'height'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'tilewidth'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'tileheight'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">width</span> = <span style="color: #008000;">self</span>.<span style="color: black;">columns</span> <span style="color: #66cc66;">*</span> <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">height</span> = <span style="color: #008000;">self</span>.<span style="color: black;">lines</span> <span style="color: #66cc66;">*</span> <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">image</span> = pygame.<span style="color: black;">Surface</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #008000;">self</span>.<span style="color: black;">width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">height</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>.<span style="color: black;">convert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># create a tileset</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name==<span style="color: #483d8b;">&quot;image&quot;</span>:
            source = attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'source'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">tileset</span> = Tileset<span style="color: black;">&#40;</span>source, <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># store additional properties.</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name == <span style="color: #483d8b;">'property'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">properties</span><span style="color: black;">&#91;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span> = attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'value'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># starting counting</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name == <span style="color: #483d8b;">'layer'</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">line</span> = <span style="color: #ff4500;">0</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">column</span> = <span style="color: #ff4500;">0</span>
        <span style="color: #808080; font-style: italic;"># get information of each tile and put on the surface using the tileset</span>
        <span style="color: #ff7700;font-weight:bold;">elif</span> name == <span style="color: #483d8b;">'tile'</span>:
            gid = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>attrs.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'gid'</span>, <span style="color: #008000;">None</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> - <span style="color: #ff4500;">1</span>
            <span style="color: #ff7700;font-weight:bold;">if</span> gid <span style="color: #66cc66;">&lt;</span><span style="color: #ff4500;">0</span>: gid = <span style="color: #ff4500;">0</span>
            tile = <span style="color: #008000;">self</span>.<span style="color: black;">tileset</span>.<span style="color: black;">get_tile</span><span style="color: black;">&#40;</span>gid<span style="color: black;">&#41;</span>
            pos = <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">column</span><span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">line</span><span style="color: #66cc66;">*</span><span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>.<span style="color: black;">image</span>.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>tile, pos<span style="color: black;">&#41;</span>
&nbsp;
            <span style="color: #008000;">self</span>.<span style="color: black;">column</span> += <span style="color: #ff4500;">1</span>
            <span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">column</span><span style="color: #66cc66;">&gt;</span>=<span style="color: #008000;">self</span>.<span style="color: black;">columns</span><span style="color: black;">&#41;</span>:
                <span style="color: #008000;">self</span>.<span style="color: black;">column</span> = <span style="color: #ff4500;">0</span>
                <span style="color: #008000;">self</span>.<span style="color: black;">line</span> += <span style="color: #ff4500;">1</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># just for debugging</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> endDocument<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">height</span>, <span style="color: #008000;">self</span>.<span style="color: black;">tile_width</span>, <span style="color: #008000;">self</span>.<span style="color: black;">tile_height</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">properties</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">self</span>.<span style="color: black;">image</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span><span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">!</span>=<span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Usage:<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\t</span>{0} filename'</span>.<span style="color: black;">format</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">sys</span>.<span style="color: black;">exit</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#41;</span>
    pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">800</span>, <span style="color: #ff4500;">480</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">parser</span> = sax.<span style="color: black;">make_parser</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    tmxhandler = TMXHandler<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">parser</span>.<span style="color: black;">setContentHandler</span><span style="color: black;">&#40;</span>tmxhandler<span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">parser</span>.<span style="color: black;">parse</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
        <span style="color: #ff7700;font-weight:bold;">for</span> event <span style="color: #ff7700;font-weight:bold;">in</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">if</span> event.<span style="color: #008000;">type</span> == QUIT:
                <span style="color: #ff7700;font-weight:bold;">return</span>
            <span style="color: #ff7700;font-weight:bold;">elif</span> event.<span style="color: #008000;">type</span> == KEYDOWN <span style="color: #ff7700;font-weight:bold;">and</span> event.<span style="color: black;">key</span> == K_ESCAPE:
                <span style="color: #ff7700;font-weight:bold;">return</span>
        screen.<span style="color: black;">fill</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>tmxhandler.<span style="color: black;">image</span>, <span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        pygame.<span style="color: black;">display</span>.<span style="color: black;">flip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">delay</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1000</span>/<span style="color: #ff4500;">60</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Here is the result for opening a four layers map file:</p>
<p><center><a href="http://silveiraneto.net/wp-content/uploads/2009/12/netbeans_python_openning_map.png"><img src="http://silveiraneto.net/wp-content/uploads/2009/12/netbeans_python_openning_map-500x375.png" alt="netbeans python openning map" title="netbeans python openning map" width="500" height="375" class="alignnone size-medium wp-image-3067" /></a> </center></p>
<p>That&#8217;s it. You can get this code and adapt for your game because next versions will be a lot more coupled for my own purposes and not so general.</p>
<p><strong>Download:</strong><a href="http://silveiraneto.net/downloads/maploader.tar.bz2"><img src="http://silveiraneto.net/wp-content/uploads/2009/12/package_32x32.png" alt="package" title="package" width="32" height="32" class="alignnone size-full wp-image-3069" />maploader.tar.bz2</a> It&#8217;s the Netbeans 6.7 (Python EA 2) project file but that can be opened or used with another IDE or without one. Also contains the village.tmx map and the tileset.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/19/tiled-tmx-map-loader-for-pygame/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Pygame: Running Orcs</title>
		<link>http://silveiraneto.net/2009/12/11/pygame-running-orcs/</link>
		<comments>http://silveiraneto.net/2009/12/11/pygame-running-orcs/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 10:47:27 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[orc]]></category>
		<category><![CDATA[Pixelart]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3048</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2009/12/11/pygame-running-orcs/" title="Pygame: Running Orcs"></a>Here is a Pygame Sprite animation using the approach presented by Joe Wreschnig and Nicolas Crovatti. It&#8217;s not yet exactly what I need but is very suitable. import pygame, random from pygame.locals import * &#160; class Char&#40;pygame.sprite.Sprite&#41;: x,y = &#40;100,0&#41; &#8230;<p class="read-more"><a href="http://silveiraneto.net/2009/12/11/pygame-running-orcs/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2009/12/11/pygame-running-orcs/" title="Pygame: Running Orcs"></a><p>Here is a <a href="http://www.pygame.org/docs/ref/sprite.html">Pygame Sprite</a> animation using the approach presented by <a href="http://www.sacredchao.net/~piman/writing/sprite-tutorial.shtml">Joe Wreschnig</a> and <a href="http://blog.shinylittlething.com/2009/07/21/pygame-and-animated-sprites/">Nicolas Crovatti</a>. It&#8217;s not yet exactly what I need but is very suitable.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> pygame, <span style="color: #dc143c;">random</span>
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Char<span style="color: black;">&#40;</span>pygame.<span style="color: black;">sprite</span>.<span style="color: black;">Sprite</span><span style="color: black;">&#41;</span>:
	x,y = <span style="color: black;">&#40;</span><span style="color: #ff4500;">100</span>,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, img, frames=<span style="color: #ff4500;">1</span>, modes=<span style="color: #ff4500;">1</span>, w=<span style="color: #ff4500;">32</span>, h=<span style="color: #ff4500;">32</span>, fps=<span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>:
		pygame.<span style="color: black;">sprite</span>.<span style="color: black;">Sprite</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
		original_width, original_height = img.<span style="color: black;">get_size</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		<span style="color: #008000;">self</span>._w = w
		<span style="color: #008000;">self</span>._h = h
		<span style="color: #008000;">self</span>._framelist = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #008000;">int</span><span style="color: black;">&#40;</span>original_width/w<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>:
			<span style="color: #008000;">self</span>._framelist.<span style="color: black;">append</span><span style="color: black;">&#40;</span>img.<span style="color: black;">subsurface</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>i<span style="color: #66cc66;">*</span>w,<span style="color: #ff4500;">0</span>,w,h<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		<span style="color: #008000;">self</span>.<span style="color: black;">image</span> = <span style="color: #008000;">self</span>._framelist<span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>		
		<span style="color: #008000;">self</span>._start = pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">get_ticks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		<span style="color: #008000;">self</span>._delay = <span style="color: #ff4500;">1000</span> / fps
		<span style="color: #008000;">self</span>._last_update = <span style="color: #ff4500;">0</span>
		<span style="color: #008000;">self</span>._frame = <span style="color: #ff4500;">0</span>
		<span style="color: #008000;">self</span>.<span style="color: black;">update</span><span style="color: black;">&#40;</span>pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">get_ticks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: #ff4500;">100</span>, <span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span>	
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> set_pos<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, x, y<span style="color: black;">&#41;</span>:
		<span style="color: #008000;">self</span>.<span style="color: black;">x</span> = x
		<span style="color: #008000;">self</span>.<span style="color: black;">y</span> = y
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> get_pos<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
		<span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">x</span>,<span style="color: #008000;">self</span>.<span style="color: black;">y</span><span style="color: black;">&#41;</span>
&nbsp;
	<span style="color: #ff7700;font-weight:bold;">def</span> update<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, t, width, height<span style="color: black;">&#41;</span>:
		<span style="color: #808080; font-style: italic;"># postion</span>
		<span style="color: #008000;">self</span>.<span style="color: black;">y</span>+=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">y</span><span style="color: #66cc66;">&gt;</span>width<span style="color: black;">&#41;</span>:
			<span style="color: #008000;">self</span>.<span style="color: black;">x</span> = <span style="color: #dc143c;">random</span>.<span style="color: black;">randint</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,height-<span style="color: #008000;">self</span>._w<span style="color: black;">&#41;</span>
			<span style="color: #008000;">self</span>.<span style="color: black;">y</span> = -<span style="color: #008000;">self</span>._h
&nbsp;
		<span style="color: #808080; font-style: italic;"># animation</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> t - <span style="color: #008000;">self</span>._last_update <span style="color: #66cc66;">&gt;</span> <span style="color: #008000;">self</span>._delay:
			<span style="color: #008000;">self</span>._frame += <span style="color: #ff4500;">1</span>
			<span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._frame <span style="color: #66cc66;">&gt;</span>= <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._framelist<span style="color: black;">&#41;</span>:
				<span style="color: #008000;">self</span>._frame = <span style="color: #ff4500;">0</span>
			<span style="color: #008000;">self</span>.<span style="color: black;">image</span> = <span style="color: #008000;">self</span>._framelist<span style="color: black;">&#91;</span><span style="color: #008000;">self</span>._frame<span style="color: black;">&#93;</span>
			<span style="color: #008000;">self</span>._last_update = t
&nbsp;
SCREEN_W, SCREEN_H = <span style="color: black;">&#40;</span><span style="color: #ff4500;">320</span>, <span style="color: #ff4500;">320</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
	pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
	screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span>SCREEN_W, SCREEN_H<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
	background = pygame.<span style="color: black;">image</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;field.png&quot;</span><span style="color: black;">&#41;</span>
	img_orc = pygame.<span style="color: black;">image</span>.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;orc.png&quot;</span><span style="color: black;">&#41;</span>
	orc = Char<span style="color: black;">&#40;</span>img_orc, <span style="color: #ff4500;">4</span>, <span style="color: #ff4500;">1</span>, <span style="color: #ff4500;">32</span>, <span style="color: #ff4500;">48</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">while</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">poll</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: #008000;">type</span> <span style="color: #66cc66;">!</span>= KEYDOWN:
		screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>background, <span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		screen.<span style="color: black;">blit</span><span style="color: black;">&#40;</span>orc.<span style="color: black;">image</span>,  orc.<span style="color: black;">get_pos</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		orc.<span style="color: black;">update</span><span style="color: black;">&#40;</span>pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">get_ticks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, SCREEN_W, SCREEN_H<span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">display</span>.<span style="color: black;">update</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">delay</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Here is it working:</p>
<p><center><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/J3oSUa6oiuk&#038;hl=pt_BR&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/J3oSUa6oiuk&#038;hl=pt_BR&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></center></p>
<p><ins datetime="2011-08-24T18:33:48+00:00">Uptade: I put this source and images at the <a href="https://github.com/silveira/openpixels/tree/master/examples/python/running_orcs">OpenPixel project in Github</a></ins></p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/11/pygame-running-orcs/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Pygame Simple Key Handling</title>
		<link>http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/</link>
		<comments>http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 03:50:39 +0000</pubDate>
		<dc:creator>Silveira</dc:creator>
				<category><![CDATA[english]]></category>
		<category><![CDATA[pygame]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://silveiraneto.net/?p=3029</guid>
		<description><![CDATA[<a href="http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/" title="Pygame Simple Key Handling"></a>Here&#8217;s a simple key handle in Pygame wheres you move a circle using keyboard. import pygame from pygame.locals import * &#160; def main&#40;&#41;: x,y = &#40;100,100&#41; pygame.init&#40;&#41; screen = pygame.display.set_mode&#40;&#40;400, 400&#41;&#41; while 1: pygame.time.delay&#40;1000/60&#41; # exit handle for event in &#8230;<p class="read-more"><a href="http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<a href="http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/" title="Pygame Simple Key Handling"></a><p>Here&#8217;s a simple key handle in <a href="http://www.pygame.org/">Pygame</a> wheres you move a circle using keyboard.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> pygame
<span style="color: #ff7700;font-weight:bold;">from</span> pygame.<span style="color: #008000;">locals</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
	x,y = <span style="color: black;">&#40;</span><span style="color: #ff4500;">100</span>,<span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span>
	pygame.<span style="color: black;">init</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
	screen = pygame.<span style="color: black;">display</span>.<span style="color: black;">set_mode</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">400</span>, <span style="color: #ff4500;">400</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
	<span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
		pygame.<span style="color: #dc143c;">time</span>.<span style="color: black;">delay</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1000</span>/<span style="color: #ff4500;">60</span><span style="color: black;">&#41;</span>
      <span style="color: #808080; font-style: italic;"># exit handle</span>
		<span style="color: #ff7700;font-weight:bold;">for</span> event <span style="color: #ff7700;font-weight:bold;">in</span> pygame.<span style="color: black;">event</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
			<span style="color: #ff7700;font-weight:bold;">if</span> event.<span style="color: #008000;">type</span> == QUIT:
				<span style="color: #ff7700;font-weight:bold;">return</span>
			<span style="color: #ff7700;font-weight:bold;">elif</span> event.<span style="color: #008000;">type</span> == KEYDOWN <span style="color: #ff7700;font-weight:bold;">and</span> event.<span style="color: black;">key</span> == K_ESCAPE:
				<span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
      <span style="color: #808080; font-style: italic;"># keys handle </span>
		key=pygame.<span style="color: black;">key</span>.<span style="color: black;">get_pressed</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_LEFT<span style="color: black;">&#93;</span>:
			x-=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_RIGHT<span style="color: black;">&#93;</span>:
			x+=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_UP<span style="color: black;">&#93;</span>:
			y-=<span style="color: #ff4500;">1</span>
		<span style="color: #ff7700;font-weight:bold;">if</span> key<span style="color: black;">&#91;</span>K_DOWN<span style="color: black;">&#93;</span>:
			y+=<span style="color: #ff4500;">1</span>
&nbsp;
		<span style="color: #808080; font-style: italic;"># fill background and draw a white circle</span>
		screen.<span style="color: black;">fill</span><span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span>,<span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">draw</span>.<span style="color: black;">circle</span><span style="color: black;">&#40;</span>screen, <span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#91;</span>x,y<span style="color: black;">&#93;</span>, <span style="color: #ff4500;">30</span><span style="color: black;">&#41;</span>
		pygame.<span style="color: black;">display</span>.<span style="color: black;">flip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>: main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Here&#8217;s a video of it working:</p>
<p><center><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/ehIqTEvAChI&#038;hl=pt_BR&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ehIqTEvAChI&#038;hl=pt_BR&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></center></p>
<p>Function <a href="http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed">pygame.key.get_pressed</a> Returns a sequence of boolean values representing the state of every key on the keyboard. It&#8217;s very useful because usually on others game platforms I have to create it by myself.</p>
<p>This approach allow me to handle more than one key at time. For example, left and up keys can be pressed and each one is handled separately creating a diagonal movement.</p>
]]></content:encoded>
			<wfw:commentRss>http://silveiraneto.net/2009/12/10/pygame-simple-key-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

