ipython automatic import at startup

In linux based system, you can configure ipython in this fold "~/.config/ipython/profile_default/".

For example, if you want ipython to automatically load frequently used imports and other thing. you can write the corresponding snippets in a py file and put it into the 'startup' directory.

when you open ipython next time, this py file will be executed, the imports and variables in which will be in the same namespace with the ipython interactive environment.

Note: if you want to sysn the configuration across different computer you used. A simple to do this is to put the configure py file into  your dropbox fold, and symbol it to the 'startup' directory.

Machine Learning With Python


Gensim – Topic Modelling for Humans


Gensim is a free Python framework designed to automatically extract semantic topics from documents, as efficiently (computer-wise) and painlessly (human-wise) as possible.

Some other packages from Blei's website. online lda, tmve(online) --Topic Model Visualization Engine, 

PyML – machine learning in Python

PyML is an interactive object oriented framework for machine learning written in Python. PyML focuses on SVMs and other kernel methods. It is supported on Linux and Mac OS X.
-----------------------------------------------------------------------------------------------

mlpy

mlpy is a Python module for Machine Learning built on top of NumPy/SciPy and the GNU Scientific Libraries.
mlpy provides a wide range of state-of-the-art machine learning methods for supervisedand unsupervised problems and it is aimed at finding a reasonable compromise among modularity, maintainability, reproducibility, usability and efficiency. mlpy is multiplatform, it works with Python 2 and 3 and it is Open Source, distributed under the GNU General Public License version 3.

scikit-learn: machine learning in Python

scikit-learn is a Python module integrating classic machine learning algorithms in the tightly-knit scientific Python world (numpy, scipy, matplotlib). It aims to provide simple and efficient solutions to learning problems, accessible to everybody and reusable in various contexts:machine-learning as a versatile tool for science and engineering.

NLTK Package

The Natural Language Toolkit (NLTK) is an open source Python library for Natural Language Processing. A free online book is available. (If you use the library for academic research, please cite the book.)
Steven Bird, Ewan Klein, and Edward Loper (2009). Natural Language Processing with Python. O’Reilly Media Inc. http://nltk.org/book

Theano

Theano is a Python library that allows you to define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays efficiently. Theano features:
  • tight integration with numpy – Use numpy.ndarray in Theano-compiled functions.
  • transparent use of a GPU – Perform data-intensive calculations up to 140x faster than with CPU.(float32 only)
  • efficient symbolic differentiation – Theano does your derivatives for function with one or many inputs.
  • speed and stability optimizations – Get the right answer for log(1+x) even when x is really tiny.
  • dynamic C code generation – Evaluate expressions faster.
  • extensive unit-testing and self-verification – Detect and diagnose many types of mistake.
Check out how Theano can be used for Machine Learning: Deep Learning Tutorials and
the source code here

sluggerml

SluggerML- baseball stats!

Using datasets from retrosheet.org and seanlahman.com/baseball-archive/statistics.

Depends on scikit-learn and python-nltk (and reportlab if you're building reports).

On Debian, requires the following to build the aforementioned:
python-dev
python-numpy
python-scipy

MDP

The Modular toolkit for Data Processing (MDP) package is a library of widely used data processing algorithms, and the possibility to combine them together to form pipelines for building more complex data processing software.

From the user’s perspective, MDP consists of a collection of units, which process data. For example, these include algorithms for supervised and unsupervised learning, principal and independent components analysis and classification.

From the developer’s perspective, MDP is a framework that makes the implementation of new supervised and unsupervised learning algorithms easy and straightforward. The basic class, Node, takes care of tedious tasks like numerical type and dimensionality checking, leaving the developer free to concentrate on the implementation of the learning and execution phases.

Simplest python server using Python

If you want to use python to build a small server or just want to provide
web-base api with minimal efforts, you can just use python SimpleHTTPServer package as below:

import SimpleHTTPServer
SimpleHTTPServer.test()

With only two lines, that's really awesome. Right? 

Or you can do as follows: 
python -m SimpleHTTPServer
the default port is 8000. 

you can also alias it in your .bash_profile file 
alias http="python -m SimpleHTTPServer"

Notes:
1. For web-based server, you can just return a json file for communication. 

2. 

Flask 

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. 
Flask is as simple as SimpleHTTPServer, but it is more powerful in many ways. You can also find rich documentation on its official website. 

Python Regular Expression

Python Regular Expressions

1. Extracting a single url OR all the urls in a text snippet 


If you're only looking for one:
import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
    print match.group(0)
If you have a long string, and want every instance of the pattern in it:
import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print ', '.join(urls)
Where s is the string that you're looking for matches in.



Compilation Flags -- inline

Python regex flags effect matching. For example: re.MULTILINE, re.IGNORECASE, re.DOTALL. Unfortunately, passing these flags is awkward if want to put regex patterns in a config file or database or otherwise want to have the user be able to enter in regex patterns. You don't want to have to make the user pass in flags separately. Luckily, you can pass flags in the pattern itself. This is a very poorly documented feature of Python regular expressions. At the start of the pattern add flags like this:
 (?i) for re.IGNORECASE
 (?L) for re.LOCALE (Make \w, \W, \b, \B, \s and \S dependent on the current locale.)
 (?m) for re.MULTILINE  (Makes ^ and $ match before and after newlines)
 (?s) for re.DOTALL  (Makes . match newlines)
 (?u) for re.UNICODE (Make \w, \W, \b, \B, \d, \D, \s and \S dependent on the Unicode character properties database.)
 (?x) for re.VERBOSE
For example, the following pattern ignores case (case insensitive):
 re.search ("(?i)password", string)
The flags can be combined. The following ignores case and matches DOTALL:
 re.search ("(?is)username.*?password", string)

Parse a simple date

This format is used by the `motion` command. This parses the date from filenames in this example format:
   02-20070505085051-04.jpg
The return format is a sequence the same as used in the standard Python library time module. This is pretty trivial, but shows using named sub-expressions.
def date_from_filename (filename):
    m = re.match(".*?[0-9]{2}-(?P[0-9]{4})(?P[0-9]{2})(?P[0-9]{2})(?P[0-9]{2})(?P[0-9]{2})(?P[0-9]{2})-(?P[0-9]{2}).*?", filename)
    if m is None:
        print "Bad date parse in filename:", filename
        return None
    day   = int(m.group('DAY'))
    month = int(m.group('MONTH'))
    year  = int(m.group('YEAR'))
    hour  = int(m.group('HOUR'))
    min   = int(m.group('MIN'))
    sec   = int(m.group('SEC'))
    dts = (year, month, day, hour, min, sec, 0, 1, -1)
    return dts

Common Short RegEx Patterns

These are some regex patterns that I have found come up often. These examples assume a string, called page, that could, for instance, be an HTML document downloaded from the web. They will return a list of all non-overlapping matches found on the page.
import urllib, re
page = ''.join( urllib.urlopen('http://www.noah.org/index.html').readlines() )

email regex pattern

It's almost impossible to match a legal email address with a small, concise regex, but this one will match most.
emails = re.findall('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', page)

URL regex pattern

According to RFC 1808, the class [!*\(\),] should really be [!*'\(\),], but single quotes are always meta-quoted in HTML files, so if I included the quote I would get extra characters in matches.
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', page)

IP address regex pattern

ips = re.findall('(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', page)

Mixing Java and Python

1. Invoking python script from Java 



import java.io.*;

public class Foo

{
    public static void main(String[] args)
    {
        try
        {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec("python foo.py");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            p.waitFor();
            String line = "";
            while (br.ready())
                System.out.println(br.readLine());

        }

        catch (Exception e)
        {
String cause = e.getMessage();
if (cause.equals("python: not found"))
System.out.println("No python interpreter found.");
        }
    }
}

The only problem with this method is that it requires the user to have a python interpreter installed on their system (and in the PATH). 


A solution for this problem is to install jython as a jar file and now I can just invoke it by including it in my class path. Here is a sample file: 



import org.python.util.PythonInterpreter;

public class Foo

{
public static void main (String[] args)
{
try
{
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("foo.py");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Note: Just make sure jython.jar is in your classpath. 



Inter-process communication of Java and Python

2. Using Socket 

3. Using jsonrpc

JSON-RPC + IDL = Barrister RPC 
This is simple. Just define your interface in a human readable IDL. 
Actually, this is the one I ended up with. 

In my cases, I use python code in the http server (Flask), and java as the client. 

The best thing is you even do not have to write any codes to call the python codes. 
Barrister RPC does everything for you since it could generate all the client codes automatically according the contract defined in the IDL. In addition, you do not have to do the data format conversion yourself. That is tedious. Barrister also does this for you in its automatically generated codes. Really cool, isn't it? 



other solutions can be found in the following presentation: 


http://elib.dlr.de/59394/1/Mixing_Python_and_Java.pdf






Python

Learn Python:

Tutorials


start ipython

ipython -p sh

Map function with multiple variable


def func1(a, b, c):
        return a+b+c
map(lambda x: func1(*x), [[1,2,3],[4,5,6],[7,8,9]])


useful packages

  • psutil : providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory, network) in a portable way by using Python
  • imp
  • sys
  • os
  • re
  • Pexpect
Pexpect is a pure Python module that makes Python a better tool for controlling and automating other programs. Pexpect is similar to the Don Libes `Expect` system, but Pexpect as a different interface that is easier to understand. Pexpect is basically a pattern matching system. It runs programs and watches output. When output matches a given pattern Pexpect can respond as if a human were typing responses. Pexpect can be used for automation, testing, and screen scraping. Pexpect can be used for automating interactive console applications such as ssh, ftp, passwd, telnet, etc. It can also be used to control web applications via `lynx`, `w3m`, or some other text-based web browser. Pexpect is pure Python. Unlike other Expect-like modules for Python Pexpect does not require TCL or Expect nor does it require C extensions to be compiled. It should work on any platform that supports the standard Python pty module.
  • Pyro4 -- Pyro means PYthon Remote Objects. It is a library that enables you to build applications in which objects can talk to eachother over the network, with minimal programming effort.
  • TkInter  Tkinter is Python's de-facto standard GUI (Graphical User Interface) package. It is a thin object-oriented layer on top of Tcl/Tk. Tkinter is not the only GuiProgramming toolkit for Python. It is however the most commonly used one. CameronLaird calls the yearly decision to keep TkInter "one of the minor traditions of the Python world."

Simplifying Python script arguments

import sys
print sys.argv
and you enter:
       python showargs.py a b c d e


run a program from within Python

  • execfile
  • subprocess.call
if you want to add augments. use the following:
subprocess.call(['./abc.py', arg1, arg2])
subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])
  • subprocess.Popen
The former can be done by importing the file you're interested in. execfile is similar to importing but it simply evaluates the file rather than creates a module out of it. Similar to "sourcing" in a shell script.
The latter can be done using the subprocess module. You spawn off another instance of the interpreter and pass whatever parameters you want to that. This is similar to shelling out in a shell script using backticks.

[edit]install python module with root previlege

mkdir -p ${HOME}/opt/lib/python2.4/site-packages/
echo "PYTHONPATH=\$PYTHONPATH:\${HOME}/opt/lib/python2.4/site-packages/" >> ~/.bashrc
echo "export PYTHONPATH" >> ~/.bashrc
echo "export PATH=\$PATH:\${HOME}/opt/bin" >> ~/.bashrc
source ~/.bashrc
easy_install --prefix=${HOME}/opt MySQL-python

How do you append directories to your Python path?

     Your path (i.e. the list of directories Python goes through to search for modules and files) is stored in the path attribute of the sys module. Since path is a list, you can use the append method to add new directories to the path.
    For instance, to add the directory /home/me/mypy to the path, just do:
    import sys 
    sys.path.append("/home/me/mypy") 
               sys.path.insert(0 , "path") #such that python will search it first. 

    How did you install the wxPython bindings? By rpm?

    As for once you know where the modules are located, you can stick something similar to the following example in $HOME/.bash_profile (or whatever the similar syntax is for your particular shell's startup scripts):

    Code:
    export PYTHONPATH=$PYTHONPATH:$HOME/lib/python:$HOME/lib/misc

    What is __init__.py used for?

      Files named __init__.py are used to mark directories on disk as a Python package directories. If you have the files
      mydir/spam/__init__.py
      mydir/spam/module.py
      and mydir is on your path, you can import the code in module.py as:
      import spam.module
      or
      from spam import module
      If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
      The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient names, hold convenience functions, etc. Given the example above, the contents of the __init__ module can be accessed as
        import spam 

      Python Regular Expressions

      Formatting

      %s Represents a value as a string
      %i Integer 
      %d Decimal integer 
      %u Unsigned integer
      %o Octal integer
      %x/%X Hexadecimal integer 
       %e/%E Float exponent
      %f/%F Floa
      %C ASCII character 

      Fancier Output Formatting for official site

      String % Dictionary
      Monica = { 
                       "Occupation": "Chef",
                       "Name" : "Monica", 
                       "Dating" : "Chandler",
                       "Income" : 40000 
                        } 
      With %(Income)d, this is expressed as
      "%(Name)s %(Income)d" % Monica 
      '40000'
      More: http://www.informit.com/articles/article.aspx?p=28790&seqNum=2

      Tips on python Collections: 

      http://alexmarandon.com/articles/python_collections_tips/



      How to use Spell checking in Python

      1. using the popen2 module in python to call the commandlines
      http://code.activestate.com/recipes/117221/

      http://blog.quibb.org/2009/04/spell-checking-in-python/

      Spell4Py is a Wrapper for Hunspell library. Org.keyphrene has been splited to several simple projects.
      There is a tutorial for Hunspell here: http://blog.keyphrene.com/keyphrene/index.php/Tutorialorgkeyphrene

      2. using a pure python program.

      http://norvig.com/spell-correct.html
      This page provides a very simple pure python spell checking program.
      You can train it with a dictionary or a textual corpus off-the-shelf with
      an accuracy around 70%.


      3. Google API
      http://developer.51cto.com/art/201103/252396.htm

      http://stackoverflow.com/questions/8428767/how-to-implement-python-spell-checker-using-googles-did-you-mean


      import httplibimport xml.dom.minidom
      
      data = """
      0" ignoredups="0" ignoredigits="1" ignoreallcaps="1">
       %s 

      """
      def spellCheck(word_to_spell):

          con
      = httplib.HTTPSConnection("www.google.com")
          con
      .request("POST", "/tbproxy/spell?lang=en", data % word_to_spell)
          response
      = con.getresponse()

          dom
      = xml.dom.minidom.parseString(response.read())
          dom_data
      = dom.getElementsByTagName('spellresult')[0]

         
      if dom_data.childNodes:
             
      for child_node in dom_data.childNodes:
                  result
      = child_node.firstChild.data.split()
             
      for word in result:
                 
      if word_to_spell.upper() == word.upper():
                     
      return True;
             
      return False;
         
      else:
             
      return True;

      Popular Posts