Archive

Archive for March, 2012

A thin Python API for wordnik.com

March 29, 2012 Leave a comment

Problem
In my current project I wanted to get the definition of a word. In addition, it’d be nice to see some examples with the given word. How to do that?

Solution
Google
In Google you can use the search term “define:word” (example). It shows you the definition, some synonyms, and it can even pronounce the word for you. Nice, but I didn’t want to parse HTML. I wanted a clean API for getting all these data.

Wiktionary
Wiktionary is an open dictionary. It has an API but I wasn’t fully satisfied with it. You can get the definition of a word as raw text (word, raw text), but it’s not that easy to extract what you want. They also provide the content in JSON format, but there the whole content was grouped in a string. Not too convenient.

Wordnik
And finally I found wordnik.com that provided exactly what I needed. They have a REST API (here), which is freely available, but first you need to request your own API key. The result is provided in JSON format. They have a Python client API but I wanted something simpler, so I wrote my own (wordnik.py).

Example

# input: barkeeper
# output:
===Definition===
(noun)
A person who owns or operates a bar for the sale of alcoholic beverages.
===Examples===
(1) Aaron called the barkeeper over and asked for a beer.
...

Related posts
I built a simple interactive, command-line dictionary that uses this thin API (see here).

invert/reverse key-value pairs in a hash

March 29, 2012 Leave a comment

Problem
You have a hash (dictionary) and you want to invert/reverse the key-value pairs. Example:

# input
map = { 'a': 1, 'b':2 }
# output
{ 1: 'a', 2: 'b' }

Solution

map = dict((v,k) for k, v in map.iteritems())

This tip is from here.

Use Case
Currently I’m working on a small application that helps one to learn new words. Reversing the dictionary of words, you can practice in both directions:

# English to Hungarian
{ 'fox': 'róka', 'hunter': 'vadász' }
# Hungarian to English
{ 'róka': 'fox', 'vadász': 'hunter' }

get screen resolution

March 27, 2012 Leave a comment

Problem
You need the current screen resolution.

Solution #1 (command-line)

xrandr | grep '*'

Sample output:

   1920x1080      50.0*    51.0     52.0

This tip is from here.

Solution #2 (Python)
Let’s see the previous solution in Python:

from jabbapylib.process import process

def get_screen_resolution():
    """
    Screen resolution (as a tuple).
    """
    result = [x for x in process.get_simple_cmd_output('xrandr').split('\n') if '*' in x][0]
    result = tuple([int(x) for x in result.split()[0].split('x')])
    return result

Sample output:

(1920, 1080)

process.get_simple_cmd_output is part of my jabbapylib library. get_simple_cmd_output() simply executes an external command and returns its output as a string.

autopy

March 26, 2012 Leave a comment

autopy is a simple, cross-platform GUI automation toolkit for Python

Installation

sudo apt-get install libxtst-dev
sudo pip install autopy

Some mouse actions

import time
import autopy as ap
from autopy.mouse import LEFT_BUTTON

def leftClick():
    ap.mouse.click(LEFT_BUTTON)
    time.sleep(.1)
    print "# click"
    
def leftDown():
    ap.mouse.toggle(True, LEFT_BUTTON)
    time.sleep(.1)
    print '# left down'

def leftUp():
    ap.mouse.toggle(False, LEFT_BUTTON)
    time.sleep(.1)
    print '# left release'
    
#############################################################################
    
if __name__ == "__main__":
    time.sleep(1)
    leftClick()
    leftDown()
    time.sleep(3)
    leftUp()

Related work (20130903)

See also pyrobot: @github, @reddit. Note that pyrobot is for Windows only.

Categories: python, windows Tags: , ,

Generate the lexicographically next permutation of a sequence

March 21, 2012 Leave a comment

Problem
You have the permutation of some elements and you want to generate its lexicographically next permutation.

Example
Take the elements [a,b,c]. Their permutations in lexicographical order:

['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
['c', 'b', 'a']

Let’s compare ‘abc‘ and ‘acb‘. Their first characters (‘a‘) are the same. Now compare the second characters: since ‘b‘ < 'c‘, ‘abc‘ is lexicographically smaller than ‘acb‘.

Algorithm

#!/usr/bin/env python

"""
Generate the lexicographically next permutation of a sequence
of elements.

Pseudo-code:

1. Find the largest index k such that a[k] < a[k + 1]. 
   If no such index exists, the permutation is the last permutation.
2. Find the largest index l such that a[k] < a[l]. 
   Since k + 1 is such an index, l is well defined and satisfies k < l.
3. Swap a[k] with a[l].
4. Reverse the sequence from a[k + 1] up to and including the final element a[n].

# from jabbapylib.math import permutation as perm
"""

def lexicographically_next_permutation(a):
    """
    Generates the lexicographically next permutation.
    
    Input: a permutation, called "a". This method modifies
    "a" in place. Returns True if we could generate a next
    permutation. Returns False if it was the last permutation
    lexicographically.
    """
    i = len(a) - 2
    while not (i < 0 or a[i] < a[i+1]):
        i -= 1
    if i < 0:
        return False
    # else
    j = len(a) - 1
    while not (a[j] > a[i]):
        j -= 1
    a[i], a[j] = a[j], a[i]        # swap
    a[i+1:] = reversed(a[i+1:])    # reverse elements from position i+1 till the end of the sequence
    return True

#############################################################################

if __name__ == "__main__":
    li = ['a', 'b', 'c']
    print li    # process
    while lexicographically_next_permutation(li):
        print li    # process

This code is part of my jabbapylib library.

Reverse a part (slice) of a list

March 21, 2012 Leave a comment

Problem
You have a list and you want to reverse a part (slice) of it.

Solution
Let our list be [1,2,9,6,5] and say we want to reverse its end from element 9, i.e. we want to get [1,2,5,6,9].

a = [1,2,9,6,5]
i = 2    # reverse from this index position
j = 4    # reverse until this index position (included)
a[i:j+1] = reversed(a[i:j+1])
print a    # [1, 2, 5, 6, 9]
Categories: python Tags: ,

amix’s blog

March 20, 2012 Leave a comment

I just found amix’s blog. He has several interesting Python posts, worth checking out.

Categories: python