Twenty things to do with a python script

From XPUB & Lens-Based wiki

With a deferential bow to Seymour Papert & Cynthia Solomon's 1971 20 Things to do with a computer, here a selected listing of Python recipes that represent a range posible explorations that need not involve much more than 20 - 30 lines of code.

Construction.gif Code/links/images to be added

<slidy theme="aa" />

Make a turtle

TurtleGrid.png

import turtle
import random
 
def Poly(n,x):
    angle = 360/n
    for i in range(n):
        turtle.forward(x)
        turtle.left(angle)
 
def makeFlower(p):
    for i in range(12):
        Poly(9,p)
        turtle.left(30)
 
def makeTriple():
    turtle.speed(44)
    for i in range(3):
        i = (i+1)*5
        turtle.color(random.random(),random.random(),random.random())
        makeFlower(i)

xa = -255  
y = -244
numberColumns = 5
numberRows = 5
turtle.penup()
turtle.setpos(xa,y)
 
for i in range(numberRows):
    for c in range(numberColumns):
        c=(c+1)*100
        makeTriple()
        turtle.penup()
        turtle.sety(y+c)
        turtle.pendown()
    i=(i+1)*100
    turtle.penup()
    turtle.setpos(xa+i,y)
    turtle.pendown()

Source: Lidia Pereira, Turtle Graphics Exercises

Create an Inkscape plugin to draw turtle graphics

LidiaTurtleGraphicsInkscape.png

See Seymour

Generate tactical hybrid texts

SocialNetworkingWithEmmaWoodhouse.png

Using nltk

Source: Femke Snelting, http://snelting.domainepublic.net/files/EmmaWoodhouse.odt

Programmatically Manipulate Typefaces

EricSchrijverProgrammaticallyManipulatingTypfaces.png

Using fontforge and robofab

Source: Eric Schrijver, http://i.liketightpants.net/and/programmatically-manipulating-typefaces

Spider texts and extract strategic search patterns

ective enforcement of intellectual property rights is critical to sustaining e
or the enforcement of intellectual property rights , taking into account diffe
procedures to enforce intellectual property rights do not themselves become ba
em of infringement of intellectual property rights , including infringement ta
ensive enforcement of intellectual property rights than is required by this Ag
etween enforcement of intellectual property rights and enforcement of law in g
lability and Scope of Intellectual property Rights 1 . This Agreement shall be
 , and maintenance of intellectual property rights . 2 . This Agreement does n
ures where a right in intellectual property is not protected under its laws an
rk for Enforcement of Intellectual property Rights ) are invoked ; ACTA / en 7
calendar days ; ( h ) intellectual property refers to all categories of intell
 to all categories of intellectual property that are the subject of Sections 1
rk for Enforcement of Intellectual property Rights ) are invoked ; ACTA / en 8
g to assert rights in intellectual property ; ( m ) territory , for the purpos
rk for Enforcement of Intellectual property Rights ), means the customs territ
 - Related Aspects of Intellectual property Rights , contained in Annex 1C to 
RK FOR ENFORCEMENT OF INTELLECTUAL property RIGHTS SECTION 1 GENERAL OBLIGATIO
ct of infringement of intellectual property rights covered by this Agreement ,
he enforcement of any intellectual property right as specified in this Section
ng the enforcement of intellectual property rights , its judicial authorities 
he infringement of an intellectual property right from entering into the chann
ng the enforcement of intellectual property rights , its judicial authorities 
s for infringement of intellectual property rights , a Party ' s judicial auth
 the right holder ' s intellectual property right in question and actually ass
horization to use the intellectual property right in question . ACTA / en 14 A

Source: Nicolas Malevé, http://vj13.constantvzw.org/live/deskcam/

Run a web server

python -m SimpleHTTPServer

Permute the spellings of search terms

LindaHilflingMisspellingGenerator.png

Source: Linda Hilfling, the experiments were developed later into the Misspelling generator browser plugin & project

Create a detourned search engine

SchmiegLorussoGoogle7.png

Source: Sebastian Schmieg & Silvio Lorusso

Create a Traceroute Map

1 week browsing.png

Source: User:Roelroscama/trim1/protoyping

Scrape Albert Heijn Loyalty Cards

http://vimeo.com/50859298

Source: Birgit Bachler, http://www.birgitbachler.com/portfolio/?p=506

Create a custom joystick sound recorder

Uses: pygame

RugzakPeterWestenberg.jpg

Source: Peter Westenberg, http://www.deschaarbeeksetaal.be/p/rugzak/

Slice & reorder an audio file by predominant frequency

DataradioSpectrumSortPlayers.png

http://kurenniemi.activearchives.org/spectrum/

Source: Nicolas Malevé and Michael Murtaugh

Create clouds of 3D objects in Blender

https://github.com/Blender-Brussels/bpy-bge-library/blob/master/scripts/bpy/duplicate_object.py

Source: Julien Deswaef, Brussels Blender Group []

Create a dotcom index using letter permuations

Screen shot 2013-04-02 at 11.52.28 AM.png

from itertools import product
chars = "abcdefghijklmnopqrstuvwxyz1234567890-"
for n in xrange(253):
    for comb in product(chars, repeat=n):
        i = ''.join(comb)
        print 'http://www.'+i+'.com'

Source: User:Roelroscama, Documentation

Filter a subtitle file to highlight the unique words of a spoken text (Disappearance)

IMG_1940.JPG

http://activearchives.org/wiki/Disappearance

#! /usr/bin/env python
# Copyright 2010 the Active Archives contributors.
# See the file AUTHORS for more details.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import re
from optparse import OptionParser
from textwrap import dedent

# inits usage and arguments
usage = "usage: %prog in.srt > out.srt"
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()

# checks the arguments length
if len(args) != 1:
    parser.error("incorrect number of arguments")

# opens the subtitle file and reads its content
try:
    f = open(args[0], 'r')
except IOError:
    sys.exit(dedent("""\
        Error: I can't open your subtitle file.
        Are you sure it exists?\
    """))
else:
    subtitles = f.read()
    f.close()

pattern = re.compile(r'[a-zA-Z]+', re.UNICODE)  # creates a pattern to search words

used_words = []
new_text = ""
previous_end = 0

# replaces all the occurrences of the words but the first one
for match in pattern.finditer(subtitles):
    new_text += subtitles[previous_end:match.start()]
    word = match.group()
    if word.lower() in used_words:
        #new_text += "*{w}*".format(w=word)
        #new_text += "<del>{w}</del>".format(w=word)
        #new_text += "--{w}--".format(w=word)
        new_text += "{w}".format(w="".ljust(len(word), " "))
    else:
        new_text += word
        used_words.append(word.lower())
    previous_end = match.end()
new_text += subtitles[previous_end:len(subtitles)]
print(new_text)

Uses: SRT, mplayer

Source: Alexandre Leray and Stéphanie_Vilayphiou

Create generative fugues

Scetchbook2011-02 markov.jpg

Voice 01 (Octave 2) File:Fugue 01 20110608.ogg
Voice 02 (Octave 3) File:Fugue 04 20110530.ogg
Voice 03 (Octave 4) File:Fugue 01-octave4 20110608.ogg

Source: Natasa Siencnik User:Natasa_Siencnik/prototyping/markov

Use open clip art and a loop to make a book of patterns

Amanofmanyparts.gif

Uses: SVG, Inkscape

 
print """<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
	 width="200px" height="50px"
	 viewBox="0 0 200 50"
	 zoomAndPan="disable" >"""

# vertical amount of elements
veramo = 20

# ydist increases the vertical distance
ydist = 10

for z in range(veramo):
    transf = "transform=\"translate({0},{1})\">".format(0,z*ydist)
    print "<g " + transf
    # horizontal amount of elements
    horamo = 20
    # ydist2 increases the vertical distance
    ydist2 = 10
    # xdist increases the horizontal distance
    xdist2 = 10
    for x in range(horamo):
        transf = "transform=\"translate({0},{1})\"".format(x*xdist,x*ydist2) 
        print "<rect " + transf + """ x="0" y="0" width="10" height="10" fill="black" />
    print "</g>"

print "</svg>"

Source: Silvio Lorusso, A man of many parts

Generating Outline Fonts with 5 Lines of Code

Douar-outline-1024x640.png

import fontforge
font = fontforge.open('douar.sfd')
for glyph in font:
    font[glyph].stroke('circular',  30, 'square', 'bevel', ('cleanup',))
font.generate('douar-new.ttf')

Uses: FontForge

Source: Ricardo Lafuente, http://blog.manufacturaindependente.org/2011/02/generating-outline-fonts-with-5-lines-of-code/

Create interactive vector graphics

http://www.stuartaxon.com/2013/03/20/natural-movement-in-python-part-3-particles/#more-331

Uses: Shoebot (http://shoebot.net/)

Source: Stuart Axon and Ricardo Lafuente

Generate an epub

http://www.ibm.com/developerworks/xml/tutorials/x-epubtut/

Other Modules to check out...

  • Manipulate images with PIL
  • use reportlab to generate a paginated PDF
  • use subprocess to run FFMPEG and scrape audio/video info using a regular expression
  • use html5lib to scrape HTML
  • use glob to process a folder full of files
  • use urllib2, urlparse and html5lib to spider HTML
  • use json to parse results from web APIs
  • use optparse to make a self-documenting command line utility
  • use random to work with some noise
  • use datetime to work easily with dates and intervals
  • use OSC to talk to control other (realtime) programs
  • use uuid to generate unique ids
  • use zipfile
  • use xml to read and extract data from an XML source