Saturday, August 29, 2009

Python - String . Random . Files

Erm. Welcome Back lol.

I am reading a book called "Introduction to Computing and Programming in Python - A multimedia Approach" by Mark Guzdial. And it use programming in JES.

Some interesting stuff here XD (U have to install Jython. Python is normally implemented in the programming language C. Jython is Python implemented in Java - this meas that Jython is actually a program written in Java. Jython lets us do multimedia that will work across multiple computer platforms.

p/s : sorry i am too lazy to paraphrase it....


10.1 Text as Unimedia
10.2 Strings: Making and Manipulating Strings
10.3 Files: Places to Put your Strings and Other Stuff
10.4 Extending Our Languages Capabilities Using Modules
10.5 Networks: Getting Our Text from the Web
10.6 Using Text to Shift Between Media

1. letter = "I am Hungry" ; print letter.find("am")
2. We can also represent trees in lists. Because lists can contain sublists, just as directories can contain subdirectories, it's a pretty easy encoding. The important point is that lists allow us to represent complex, hierarchical relationships, like trees.

>>> tree = [["Leaf1","Leaf2"],[["Leaf3"],["Leaf4"],"Leaf5"]]
>>>print tree[1][0]

10.3 Opening and Manipulating Files
  • 'rt' means 'read the file as text - translate the bytes into characters for me
  • 'wt' means write the file as text
  • 'rb' and 'wb' mean 'read and write bytes'. you use these if you are going to manipulate binary files(Like JPEG, WAV, Word or Excel files)
The function open() returns a file object that you then use to manipulate the file. The file object understands a set of methods.
  • reads the whole file as a giant string.
  • file.readlines() reads the whole file into a list where each element is a single line. You can only use read() or readlines() once per file opening.
  • file.write(somestring) writes somestring to the file.
  • file.close() close the file. If you were writing to the file, closing to it makes sure that all the data gets writen out on the disk.

def formletter(gender, lastname, city, eyecolor):
file = open("formletter.txt", "wt")
file.write("dear ")
if gender == "F":
if gender == "M":

# A program to change the littlepicture program with find() and addText() function
def changeLittle(filename, newstring):
#Get teh original file contents
programfile = ""
file = open(programfile, "rt")
contents =
#Now find the right place to put our new string
addtext = contents.find("addText")
#Double quote after addText
firstquote = contents.find(' " ', addtext)
#Double quote after firstquote
endquote = contents.find(' " ', firstquote+1)
#Make our new file
newfile = open(filename, "wt")
newfile.write(contents[:firstquote+1])#include the quote

#Finding a subsequence in parasite nucleotide sequences
def findsequence(seq):
sequencesfile = getmediapath("parasites.txt")
file = open(sequencesfile, "rt")
sequences =
#find the sequence
seqloc = sequences.find(seq)
#print "Found at", seqloc
if seqloc <> -1:
#Now, find the ">" with the name of the sequence
nameloc = sequences.rfind(">",0,seqloc)
#print "Name at:", nameloc
endline = sequences.find("\n,nameloc")
print "FOund in ", sequences [nameloc:endline]
if seqloc == -1:
print "Not found"

how it works:
The function findsequence takes a part of a sequence as an input. It opens the parasites.txt file and reads the whole thing into the string sequences. We look for the sequence in the string sequences using find. If it's found (ie the result isn't -1), then we look backwards from where we found the sequence (seqloc) to the beginning of the string(0) to find the ">" which starts the sequence. We then search forward from the greater-than sign to the end of the line ("\n").
This gives us where in the original sequences string we can find the name of the parasite that our input subsequence is form.


In every programming language, there is a way of extending the basic funcions of the language with new ones. In python, this functionality is referred to as importing a module. A module is simply a python file with new capabilities defined in it. when you import a module, it's as if you typed that python file in at that point and all the objects, functions, and variables in it become defined at once. Python comes with an extensive library of modules that you can use to do a wide range of things, such as accessing the Internet, generating random numbers, and accessing files in a directory - a useful thing to do when developing webpages or working with videos.

>>>import os
>>>print os.listidr("C:\Documents and Settings\Mark\Mydocuments\pics")

#Title a set of pictures in a directory
import os
def titleDirectory(dir):
for file in os.listdir(dir):
print "Processing:", dir+"//"+file
if file.endswith(".jpg"):
picture = makePicture(dir+"\\"+file)
addtect(picture,10,10,"Property of CS")

HowItWorks: The function titleDirectory takes a directory(pathname, as a string) as input. It then walks through each filename file in the directory. If the filename ends with ".jpg" it's probably a picture. So we make the picture from the file in the given dir directory. We add text to the picture, then write the picture back out as "titled=" plus the filename, in the given dir directory.

Another Fun Module : Random

import random
>>> for i in range (1.10):
print random.random()

>>>for i in range(1.5):
print random.choice(["a","b","c"])

No comments: