Assignment 7 Helps

| categories: Info

Here are some short code fragments to help you with Assignment 7.

Write data to a file.

# get the subject id
subj = raw_input('Enter subject id: ')

# construct a name for this data set
file_name = 'data/' + subj + '.txt'
# create a file object with the given name
fp = file(file_name, 'w')

# data collection code goes here
for i in range(5):
    word = raw_input('enter word: ')
    # suppose I wanted to record the number and the word
    print >>fp, str(i) + '|' + word

fp.close() # close the file object and make sure all data is written

Make a prompt appear and disappear after a short time.

import sys
import time

def promptThenDisappear(prompt, timeToDisplay):
    # write the prompt
    sys.stdout.write(prompt)
    # make sure the user can see it
    sys.stdout.flush()
    # wait for the specified time
    time.sleep(timeToDisplay)
    # erase it
    sys.stdout.write('\r' + ' '*len(prompt) + '\n')
    sys.stdout.flush()

# example of using it

promptThenDisappear('test', 2)

Compare two strings and get a score from 0 to 1 for their similarity.

import difflib
def stringSimilarity(a, b):
    sm = difflib.SequenceMatcher(None, a, b)
    return sm.ratio()

Change the color of text in the console.

import os
import sys

if os.name == 'nt':
    # windows version
    colors = {
        'black': 0,
        'blue': 1,
        'green': 2,
        'cyan': 3,
        'red': 4,
        'magenta': 5,
        'yellow': 6,
        'white': 7
    }
    import ctypes
    handle = ctypes.windll.kernel32.GetStdHandle(-11)
    def setColor(textColor, backgroundColor):
        color = colors[backgroundColor]<<4 | colors[textColor] | 0x88
        r = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)

else:        
    # non windows version
    colors = {
        'black': 0,
        'red': 1,
        'green': 2,
        'yellow': 3,
        'blue': 4,
        'magenta': 5,
        'cyan': 6,
        'white': 7
    }
    def setColor(textColor, backgroundColor):
        color = '\x1b[3%d;4%d;1m' % (colors[textColor], colors[backgroundColor])
        sys.stdout.write(color)

# examples of using it

# setColor('red', 'green')
# print 'this is red text on green background'

Display a picture for a short time.

import numpy as np
import pylab

# read the image. You could read several of course. You'll need to change the name below
pic = pylab.imread('mypic.jpg')

# create a black image the same size to use for hiding
black = np.zeros_like(pic)

# turn on interactive mode so the plot will update while the script is running
pylab.ion()

# show the picture
pylab.imshow(pic)

# wait for 1/2 second. Change the value of timeout to increase or decrease the time
pylab.ginput(timeout=0.5)

# display the black image instead
pylab.imshow(black)

# force the black image to display
pylab.draw()