User:Alvations/py cheatsheet
I am sort of new to python programming though not new to programming so here I've compiled some recipes that I often used in my NLP pursuit.
String Manipulation
Insert a substring into a string
Often I want to insert a character or substring at a specified position. I've no idea why python strings doesn't have an in-built insert though.
# To insert a string into an original string at a specified position. def insert(original, insertee, pos): return original[:pos:] + insertee + original[pos:] print insert ("hoses", "r", 2)
List/Sets Manipulation
Find the difference between 2 lists
Without further ado, ...
# Returns the difference between 2 lists. def getDiff(lista, listb): return [x for x in lista if x not in listb]
Find the overlap between 2 lists
I'm kind of a Lesk algorithm junkie so I always want to find overlaps between 2 lists/maps/set/dicts/etc.
# Returns the overlap between 2 lists. def getOverlap(lista, listb): return [x for x in lista if x in listb]
Dictionary/Collections Manipulation
Find the first instance of a key given a value in a dictionary
# Gets first instance of matching key given a value and a dictionary. def getKey(dic, value): return [k for k,v in sorted(dic.items()) if v == value]
pyDev/pyLucene v2.3 Related Issues/Recipes
Most of the following installation related hint are based on my Ubuntu 12.04 LTS distro. The pyLucene recipes are independent on the OS but it's based on pylucene version 2.3.
How to install pyDev in Eclipse IDE?
Firstly get the Eclipse IDE, I prefer to install and start the Eclipse IDE through the terminal by:
$ sudo apt-get install eclipse-platform $ eclipse
To install pyDev, the pyDev mainsite has an installation page with instructions and screenshots, see http://pydev.org/manual_101_install.html
How to install pyLucene?
The following instructions installs pylucene v2.3 based on openjdk-6
$ sudo apt-get install openjdk-6-jdk openjdk-6-jre-headless openjdk-6-jre-lib $ sudo apt-get install ant ant-doc ant-optional $ sudo apt-get install ivy ivy-doc $ sudo apt-get install pylucene $ sudo apt-get install python-dev $ ldconfig -p | grep libjvm
Now you should be able to run a pylucene code on your machine, a sample code can be found on http://www.tomergabel.com/ScriptingLuceneWithPython.aspx