Week 6

From Expressive Computing

Contents

Some text-oriented work

A tentative list. Not necessarily related to one another. (See Week 8 or Project 3 for a more extensive list)

Why Python?

Here's the party line.

For our purposes, Python is ideal because it has simple and elegant idioms for working with files, strings, and lists. It lets us get down to the real business of munging text without having to worry about technicalities. Just as an example, here are two programs, both of which do the same thing: visit every line in a file and print the first three characters on each line.

First, in Java:

import java.io.*;
class TextTest {
  public static void main(String args[]) {
    String line;
    try {
      BufferedReader stdin =
        new BufferedReader(new InputStreamReader(System.in));
      while ((line = stdin.readLine()) != null) {
        if (line.length() >= 3) {
          System.out.println(line.substring(0, 3));
        }
        else {
          System.out.println(line);
        }
      }
    } 
    catch (IOException e) {
      System.err.println("Error: " + e);
    }
  }
}

The equivalent in Python:

import sys
for line in sys.stdin:
  print line[0:3]

Sample code and text from this week

Download here. Includes several Python scripts and a number of sample texts.

Resources for Learning and Using Python

Reading for next week

Six Selections by the Oulipo, NMR pp. 147-189.

Home