Friday, April 25, 2014

Feature Idea for Blogging Software

When presenting the user with the list of tags applied to a post, how about you omit any tag that has only 1 member (i.e. the post you just read)?

Clicking on such a tag is a total waste of time.

Calling the patent attorney now...

Friday, April 18, 2014

Python speech synthesis on OS X

I know, this is cheating. But it's fun.

def speak(*args):
    from subprocess import Popen, PIPE
    cmd = ["/usr/bin/say"]
    Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()

Tuesday, April 8, 2014

Copying text via Python on OS X (revisited)

Let's try that again.

import Cocoa
pb = Cocoa.NSPasteboard.generalPasteboard()

def get_clipboard_text():
    """Get the text contents of the system clipboard. 
    @return (string)
    return pb.stringForType_(Cocoa.NSPasteboardTypeString)

def copy_text_to_clipboard(text):
    """Copy the supplied text to the clipboard.
    @param text
    pb.declareTypes_owner_([Cocoa.NSPasteboardTypeString], None)
    pb.setString_forType_(text, Cocoa.NSPasteboardTypeString)

Wednesday, December 12, 2012

Copying text via Python on OS X

It took me an embarrassingly long time to figure out why I was getting an extra newline character appended to the copied text. (It was because I forgot to include the -n parameter to echo.)

from subprocess import Popen, PIPE

def copy_to_clipboard(self, text):
    # equivalent to: echo "text" | pbcopy
    p1 = Popen(['/bin/echo', '-n', text], stdout=PIPE)
    p2 = Popen(['/usr/bin/pbcopy'], stdin=p1.stdout, stdout=PIPE, stderr=PIPE)

def get_clipboard_text(self):
    return Popen(['/usr/bin/pbpaste', '-Prefer', 'txt'], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate()[0]

Friday, April 20, 2012

Igpay Atinlay

def pig_latinize(text):
    Returns the Pig Latin version of the supplied English text.
    @return (string) Pig Latin
    import string

    new_text = ''

    for word in text.split():
        punctuation_mark_begin = ''
        punctuation_mark_end   = ''

        if word[-1] in string.punctuation:
            punctuation_mark_end   = word[-1]
            word = word[:-1]

        if word[0]  in string.punctuation:
            punctuation_mark_begin = word[0]
            word = word[1:]

        all_caps   = word == word.upper()
        title_caps = word[0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

        word = word.lower()

        new_word = None

        m = len(word)

        if m < 3 or word in ['and', 'the']:
            new_word = word + 'kay'

            vowel_offsets = [word.find(v) for v in 'aeiouy' if (word.find(v) != -1)]

            m = 0 if (len(vowel_offsets) == 0) else min(vowel_offsets)

            if m == 0:
                new_word = word + 'way'
                new_word = word[m:] + word[:m] + 'ay'

        if all_caps and (len(new_word) > 1):
            new_word = new_word.upper() 

        elif title_caps:
            new_word = new_word[0].upper() + new_word[1:]

        new_text += punctuation_mark_begin + new_word + punctuation_mark_end + ' '

    return new_text[:-1]

INKAY ONGRESSCAY, ULYJAY 4KAY, 1776WAY Thekay unanimousway Eclarationday ofkay thekay irteenthay unitedway Atesstay ofkay Americaway Enwhay inkay thekay Oursecay ofkay umanhay eventsway itkay ecomesbay ecessarynay orfay oneway eoplepay tokay issolveday thekay oliticalpay andsbay ichwhay avehay onnectedcay emthay ithway anotherway andkay tokay assumeway amongway thekay owerspay ofkay thekay earthway, thekay eparatesay andkay equalway ationstay tokay ichwhay thekay Awslay ofkay Aturenay andkay ofkay Ature'snay Odgay entitleway emthay, akay ecentday espectray tokay thekay opinionsway ofkay ankindmay equiresray atthay eythay ouldshay eclareday thekay ausescay ichwhay impelway emthay tokay thekay eparationsay.

Oodgay enoughway.

Thursday, November 17, 2011

str() is the Devil

Recently I discovered the folly of using str() within Python 2.7 scripts. My program would ingest arbitrary UTF8 text from outside sources and then try to print it to a file, only to crash with a UnicodeDecodeError or UnicodeEncodeError exception. In good time, I realized how to do it The Right Way and converted all my str() calls to unicode().

But the error kept occurring. It took me quite a while to remember that

foobar = ''

is functionally equivalent to

foobar = str()

This problem shouldn't happen in Python 3, since all strings are Unicode by default there.

Thursday, September 15, 2011

How to turn a list outside-in

def turnListOutsideIn(aList):
	Returns a new list containing the 1st element, then the last,
	then the 2nd, then the next-to-last, etc.

	# create a reversed copy of the original list
	revList = list(aList)

	# zip them together as a list of tuple pairs
	zippedList = zip(aList, revList)

	# flatten the list
	flatList = [inner for outer in zippedList for inner in outer]

	# return the first half of the list
	return flatList[0:len(aList)]

digits = range(10)
print outsideInList(digits)
[0, 9, 1, 8, 2, 7, 3, 6, 4, 5]