python recipe: open a file, read it, print matching lines . palewire There are a couple great books available free online but it's pretty tough to start stringing all the fundamentals into a problem-solving script all on your own. So why not write up some simple recipes that attack problems common to our particular tribe? One of the ways computer programming can be of great use to a reporter is as a text parser. If it's a one-off effort, you can probably get this done quickly using search tools included in common quality text editors (ex. In that spirit, the following instructions are designed to show you how to use Python to search through a text file (The Sonnets of William Shakespeare), find any lines that contain our sample search term ("love"), and then print out the hits into a new file we can keep as a memento. The one prerequsite for the whole endeavor is that you already have a working installation of Python. If you've got it properly installed, it should return something like Alright, with all that out of the way, let's get to the recipe. 1. 2. #!
Multiple Function Arguments - Learn Python - Free Interactive Python Tutorial Every function in Python receives a predefined number of arguments, if declared normally, like this: def myfunction(first, second, third): # do something with the 3 variables ... Execute Code It is possible to declare functions which receive a variable number of arguments, using the following syntax: def foo(first, second, third, *therest): print "First: %s" % first print "Second: %s" % second print "Third: %s" % third print "And all the rest... The "therest" variable is a list of variables, which receives all arguments which were given to the "foo" function after the first 3 arguments. First: 1 Second: 2 Third: 3 And all the rest... [4, 5] It is also possible to send functions arguments by keyword, so that the order of the argument does not matter, using the following syntax: The following code yields the following output: The sum is: 6 Result: 1 The "bar" function receives 3 arguments.
Python Sending Email using SMTP Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending e-mail and routing e-mail between mail servers. Python provides smtplib module, which defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail − import smtplib smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] ) Here is the detail of the parameters: host: This is the host running your SMTP server. An SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a message. The sender - A string with the address of the sender.The receivers - A list of strings, one for each recipient.The message - A message as a string formatted as specified in the various RFCs. Example Here is a simple way to send one e-mail using Python script. #! smtplib.SMTP('mail.your-domain.com', 25) Sending an HTML e-mail using Python #! #!
Why are Python's 'private' methods not actually private Classes and Objects - Learn Python - Free Interactive Python Tutorial Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects. A very basic class would look something like this: class MyClass: variable = "blah" def function(self): print "This is a message inside the class." Execute Code We'll explain why you have to include that "self" as a parameter a little bit later. myobjectx = MyClass() Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass". Accessing Object Variables To access the variable inside of the newly created object "MyObject" you would do the following: myobjectx.variable So for instance the below would output the string "blah": print myobjectx.variable You can create multiple different objects that are of the same class(have the same variables and functions defined). myobjecty = MyClass() myobjecty.variable = "yackity"
Python Networking Programming Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols. Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on. This chapter gives you understanding on most famous concept in Networking - Socket Programming. What is Sockets? Sockets are the endpoints of a bidirectional communications channel. Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. Sockets have their own vocabulary: The socket Module To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax − s = socket.socket (socket_family, socket_type, protocol=0) Here is the description of the parameters − Server Socket Methods Client Socket Methods
Learn Python The Hard Way, 3rd Edition Python is called an "object-oriented programming language." This means there is a construct in Python called a class that lets you structure your software in a particular way. Using classes, you can add consistency to your programs so that they can be used in a cleaner way. I am now going to teach you the beginnings of object-oriented programming, classes, and objects using what you already know about dictionaries and modules. Here we go. You know how a dictionary is created and used and that it is a way to map one thing to another. Keep this idea of "get X from Y" in your head, and now think about modules. A Python file with some functions or variables in it ..You import that file.And you can access the functions or variables in that module with the . Imagine I have a module that I decide to name mystuff.py and I put a function in it called apple. Once I have this code, I can use the module MyStuff with import and then access the apple function: I can access that the same way:
An Introduction to Python Lists You can use the list type to implement simple data structures, such as stacks and queues. stack =  stack.append(object) object = stack.pop() queue =  queue.append(object) object = queue.pop(0) The list type isn’t optimized for this, so this works best when the structures are small (typically a few hundred items or smaller). For larger structures, you may need a specialized data structure, such as collections.deque. Another data structure for which a list works well in practice, as long as the structure is reasonably small, is an LRU (least-recently-used) container. lru.remove(item) lru.append(item) If you do the above every time you access an item in the LRU list, the least recently used items will move towards the beginning of the list. Searching Lists The in operator can be used to check if an item is present in the list: if value in L: print "list contains", value To get the index of the first matching item, use index: i = L.index(value) try: i = L.index(value) except ValueError: i = -1
Python Regular Expressions A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The module re provides full support for Perl-like regular expressions in Python. We would cover two important functions, which would be used to handle regular expressions. The match Function This function attempts to match RE pattern to string with optional flags. Here is the syntax for this function − re.match(pattern, string, flags=0) Here is the description of the parameters: The re.match function returns a match object on success, None on failure. Example #! When the above code is executed, it produces following result − matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter The search Function This function searches for first occurrence of RE pattern within string with optional flags. Here is the syntax for this function: #! #! No match!!
2.6. Image manipulation and processing using Numpy and Scipy — Scipy lecture notes This chapter addresses basic image manipulation and processing using the core scientific modules NumPy and SciPy. Some of the operations covered by this tutorial may be useful for other kinds of multidimensional array processing than image processing. In particular, the submodule scipy.ndimage provides functions operating on n-dimensional NumPy arrays. Image = 2-D numerical array (or 3-D: CT, MRI, 2D + time; 4-D, ...) Here, image == Numpy array np.array Tools used in this tutorial: numpy: basic array manipulationscipy: scipy.ndimage submodule dedicated to image processing (n-dimensional images). Common tasks in image processing: Input/Output, displaying imagesBasic manipulations: cropping, flipping, rotating, ...Image filtering: denoising, sharpeningImage segmentation: labeling pixels corresponding to different objectsClassificationFeature extractionRegistration... More powerful and complete modules: OpenCV (Python bindings)CellProfilerITK with Python bindingsmany more... 2.6.1. 2.6.2. 2.6.3.
Modules and Packages - Learn Python - Free Interactive Python Tutorial Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command. To import a module, we use the import command. Check out the full list of built-in modules in the Python standard library here. The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If we want to import the module urllib, which enables us to create read data from URLs, we simply import the module: # import the library import urllib # use it urllib.urlopen(...) Execute Code Exploring built-in modules Two very important functions come in handy when exploring modules in Python - the dir and help functions. We can look for which functions are implemented in each module by using the dir function: When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter: help(urllib.urlopen) import foo.bar