background preloader

The Python “with” Statement by Example

The Python “with” Statement by Example
Python’s with statement was first introduced five years ago, in Python 2.5. It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it: with open('output.txt', 'w') as f: f.write('Hi there!') The above with statement will automatically close the file after the nested block of code. Here’s another example. This code sample uses a Context object (“cairo context”) to draw six rectangles, each with a different rotation. cr.translate(68, 68) for i in xrange(6): cr.save() cr.rotate(2 * math.pi * i / 6) cr.rectangle(-25, -60, 50, 40) cr.stroke() cr.restore() That’s a fairly simple example, but for larger scripts, it can become cumbersome to keep track of which save goes with which restore, and to keep them correctly matched. By themselves, pycairo’s save and restore methods do not support the with statement, so we’ll have to add the support on our own.

Understanding Python's "with" statement Fredrik Lundh | October 2006 | Originally posted to online.effbot.org Judging from comp.lang.python and other forums, Python 2.5’s new with statement (dead link) seems to be a bit confusing even for experienced Python programmers. As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code: set things up try: do something finally: tear things down Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. def controlled_execution(callback): set things up try: callback(thing) finally: tear things down def my_function(thing): do something controlled_execution(my_function) This wasn’t very difficult, was it?

Twitter sentiment analysis using Python and NLTK | Laurent Luce's Blog This post describes the implementation of sentiment analysis of tweets using Python and the natural language toolkit NLTK. The post also describes the internals of NLTK related to this implementation. Background The purpose of the implementation is to be able to automatically classify a tweet as a positive or negative tweet sentiment wise. The classifier needs to be trained and to do that, we need a list of manually classified tweets. Positive tweets: I love this car.This view is amazing.I feel great this morning.I am so excited about the concert.He is my best friend. Negative tweets: I do not like this car.This view is horrible.I feel tired this morning.I am not looking forward to the concert.He is my enemy. In the full implementation, I use about 600 positive tweets and 600 negative tweets to train the classifier. Next is a test set so we can assess the exactitude of the trained classifier. Test tweets: Implementation The following list contains the positive tweets: Classifier Classify Voilà.

NPR Puzzle: Finding Synonyms with Python and WordNet | Data Dork This week’s puzzle asks: From Alan Meyer of Newberg, Ore.: Think of a common word that’s six letters long and includes a Q. Change the Q to an N, and rearrange the result to form a new word that’s a synonym of the first one. What are the words? This puzzle is a good opportunity to play with some very cool computational language tools available through the Natural Langauge Toolik (NLTK). Before we get to using the NLTK, let’s break down this puzzle into multiple steps. 1. Approach: 1. 2. 3. This is best demonstrated through example and the use of one our language’s most versatile words – shit. So what I’ve done here is started Python in the terminal, and then installed the wordnet module from nltk.corpus. Back to the puzzle at hand, we need to see if any of the words from step 1 and step 2 are synonyms. Going through all the word pairs generated in step 1 and 2, I find there is only one pair of words that satisfy all constraints – uneasy and queasy. Full code available here at github here.

20 Tools & Converters for HTML to RSS Conversions Do you have a static HTML website, but you want to either turn this content into an RSS Feed or add an RSS feed to your web site? Then this is the list that will make you very happy. This is the ultimate list of free tools to turn any static web page into an XML RSS feed. These tools are very useful to both web savvy users as well as the non-geek user who has no idea how to read or use HTML. The RSS Wizard This is a program that will allow you to generate an RSS 2.0 feed from any type of HTML document. DapperDapper allows anyone to create Dapps that track the content of any website. Feed43Your favorite site doesn’t provide news feeds? FeedityCreate RSS for ANY web page! FeedXSThis is a great service that allows you to create as many RSS feeds as you need. FeedmarkletFeedmarklet automatically extracts the location and title of the page that you are reading, saving you the time of entering this information into a form. Feed Fire RSS Builder

How not to write Python code Lately I’ve been reading some rather unclean Python code. Maybe this is mainly because the author(s) of the code had no in-depth knowledge of the Python language itself, the ‘platform’ delivered with cPython,… Here’s a list of some of the mistakes you should really try to avoid when writing Python code: Some days ago RealNitro pointed me at this list of essential Python readings. That’s about it for now, maybe I’ll add some more items to this list later on. Posted in Development, Technology. Tagged with Development, python. By Nicolas – February 8, 2008 13 cours en ligne gratuits sur l’Open Data Belle initiative du Portail européen des données qui propose depuis mars 2016, une série de 13 cours en ligne d’autoformation sur l’Open Data (données ouvertes) : Programme e-learning du Portail Européen des Données, une séquence de formation ouverte et à distance (FOAD) lancée dans le cadre de l’Open Data Day le 5 mars 2016. Ces 13 modules en ligne en accès libre permettent d’appréhender les différentes facettes de l’Open Data via des textes informatifs, des infographies, des vidéos, des images et des QCM récapitulatifs. Les différents cours peuvent être suivis étape par étape ou indépendamment les uns des autres. Ces modules proposent aussi la découverte d’outils et d’une méthodologie éprouvée. Cours 1 – L’open data, c’est quoi ? Licence : Contrat spécifique : merci de prendre contactGéographie : Europe Tags: autoformation, cours, Europe, formation, open data, outil en ligne, pédagogie, univers libre

Book Natural Language Processing with Python – Analyzing Text with the Natural Language Toolkit Steven Bird, Ewan Klein, and Edward Loper This version of the NLTK book is updated for Python 3 and NLTK 3. The first edition of the book, published by O'Reilly, is available at (There are currently no plans for a second edition of the book.) 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Bibliography Term Index This book is made available under the terms of the Creative Commons Attribution Noncommercial No-Derivative-Works 3.0 US License.

BeginnersGuide/Programmers This is a Wiki page. Users with edit rights can edit it. You are, therefore, free to (in fact, encouraged to) add details of material that other Python users will find useful. It is not an advertising page and is here to serve the whole Python community. Users who continually edit pages to give their own materials (particularly commercial materials) prominence, or spam the listing with multiple entries which point to resources with only slightly altered material, may subsequently find their editing rights disabled. You have been warned. A beginner-friendly Python tutorial that starts with the absolute basics but also covers more advanced stuff like Python software deployment. Text Processing in Python (a book) A couple of you make donations each month (out of about a thousand of you reading the text each week). Tragedy of the commons and all that... but if some more of you would donate a few bucks, that would be great support of the author. In a community spirit (and with permission of my publisher), I am making my book available to the Python community. Minor corrections can be made to later printings, and at the least errata noted on this website. Email me at <mertz@gnosis.cx> . A few caveats: (1) This stuff is copyrighted by AW (except the code samples which are released to the public domain).

Think Python: How to Think Like a Computer Scientist How to Think Like a Computer Scientist by Allen B. Downey This is the first edition of Think Python. It uses Python 2, with notes on differences in Python 3. Buy this book at Amazon.com Download Think Python in PDF. Read Think Python in HTML. Example programs and solutions to some problems are here (links to specific examples are in the book). Description Think Python is an introduction to Python programming for beginners. Some examples and exercises are based on Swampy, a Python package written by the author to demonstrate aspects of software design, and to give readers a chance to experiment with simple graphics and animation. Think Python is a Free Book. If you have comments, corrections or suggestions, please send me email at feedback{at}thinkpython{dot}com. Other Free Books by Allen Downey are available from Green Tea Press. Download Precompiled copies of the book are available in PDF. Python 3.0 Most of the book works for Python 2.x and 3.0. Michael Kart at St. Earlier Versions

Related: