Wednesday, April 14, 2010

Python - frequency and location of words in text

# Split a paragraph into lines and find 
# the frequency and line number of words. 
 
from operator import itemgetter
 
# words and locations are stored in a dict 
wordDict = {}
 
# the text we will parse 
text = ''' this is the text on line one. 
this is line two text. 
here is the text of line number three.''' 
 
 
def groupWords(text):
    lineCount = 0
    # break down by lines 
    for line in text.split('\n'):
        line = line.strip(".,!?:;'") # strip puncuation 
        lineCount += 1
        upLine = line.upper() # words are words..case no matter 
        # break line into words 
        for word in upLine.split():
            if wordDict.has_key(word):
                # then add to the key 
                tempValue = wordDict[word]
                wordDict[word] = str(tempValue) + " " + str(lineCount)
            else:
                # add it 
                wordDict[word] = " " + str(lineCount)
 
groupWords(text)
 
# alphabetical output 
for k in sorted(wordDict.iterkeys()):
    print k + str(wordDict[k])
 
# my output: 
##  HERE 3 
##  IS 1 2 3 
##  LINE 1 2 3 
##  NUMBER 3 
##  OF 3 
##  ON 1 
##  ONE 1 
##  TEXT 1 2 3 
##  THE 1 3 
##  THIS 1 2 
##  THREE 3 
##  TWO 2 
 
# most frequent style output 
# put the dict in a list 
wordList = []
for k in wordDict.iterkeys():
    wordList.append((str(len(wordDict[k].replace(' ',''))),
                    str(k),
                    wordDict[k]))
 
 
for word in sorted(wordList, key=itemgetter(0), reverse=True):
    print word[0], word[1], ":"+word[2]
 
# my output: 
##  3 TEXT : 1 2 3 
##  3 IS : 1 2 3 
##  3 LINE : 1 2 3 
##  2 THIS : 1 2 
##  2 THE : 1 3 
##  1 ON : 1 
##  1 TWO : 2 
##  1 HERE : 3 
##  1 ONE : 1 
##  1 NUMBER : 3 
##  1 OF : 3 
##  1 THREE : 3 
 
 

Monday, April 12, 2010

Python - Finding GCD with Euclids Algorithm

# Implementing the Euclidean Algorithm
# is simple in python.
#
# Euclid's algorithm is used to efficiently
# find two numbers greatest common divisor (GCD)
 
# Division based Euclidean algorithm
def gcd(a,b):
    while b != 0:
        temp = b
        b = a%b
        a = temp
    return a
 
# Recursive based Euclidean algorithm
def recursiveGCD(a,b):
    if b==0:
        return a
    else:
        return recursiveGCD(b, a%b)
 
 
# just to prove they both work the same:
def findGCD(a,b):
    divisionStyle = gcd(a,b)
    recursiveStyle = recursiveGCD(a,b)
    if divisionStyle != recursiveStyle:
        return "Fail...GCDs differ"
    else:
        return divisionStyle
 
print findGCD(1071, 462)
print findGCD(5, 10)
print findGCD(5214, 24324)
 
# my output:
#   21
#   5
#   6
 
 
 

Wednesday, April 7, 2010

Python - Tkinter frontend example to ping

# python GUI example using Tkinter

# Everyone likes to ping servers and what
# not so this example is a front end
# to the well used ping command.
#
# Python has quite a few different

# frameworks to choose from. For
# this example I'll use the basic
# Tkinter that ships with most python
# installers.

#

from Tkinter import *
from subprocess import PIPE, Popen

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.grid()

        # create and position widgets

        self.label = Label(frame, text="Enter IP Address or Server Name:")
        self.label.grid(row=0, column=0, sticky=W)

        self.textbox = Text(frame, height=1, width=40)
        self.textbox.grid(row=1, column=0, columnspan=2, sticky=W)
        self.textbox.insert(END, "www.google.com")

        self.resultsBox = Text(frame, height=10, width=60)
        self.resultsBox.grid(row=3, column=0, columnspan=3, sticky=W)

        self.hi_there = Button(frame, text="Ping",
                               width=10, command=self.doPing)
        self.hi_there.grid(row=1, column=2, sticky=W)

    def doPing(self):
        # reset result box
        self.resultsBox.delete(1.0, END)
        # get text

        texttext = self.textbox.get(1.0, END)
        exelist = ['ping', '-n', '1']
        exelist.append(texttext)
        # Execute command (these ping commands are windows specific).
        # In Linux you would use the '-c' to specify count.

        exe = Popen(exelist, shell=False, stdout=PIPE, stderr=PIPE)
        out, err = exe.communicate()
        while out:
            self.resultsBox.insert(END, out)
            out, err = exe.communicate()

root = Tk()
app = App(root)
root.mainloop()


Python - event programming example

# Event programming in python

# Python doesn't have a standard 'only' way
# of doing events.  You can create your own
# pythonic events like so.
#

# In the example you'll notice that the Musician
# handles all the recieved events.  You could
# have just as easily created specific event
# handlers for the reacting classes.  Whatever

# makes sense for your application is good.
# Python is flexible!
#
# This would be a way that
# python could implement events or delegates.

import time

# Important class that will raise events
class Orchestrator(object):
    def __init__(self):
        # You'll notice that the events instances

        # of the subscribers are stored in these
        # lists.  Having a list allows multiple
        # subscribers to the event.
        self.armsRaise = []
        self.pointsAtMe = []
    def subscribeToArmRaiseEvent(self, event):
        # we append the instance methods to the

        # event lists
        self.armsRaise.append(event)
    def subscribeToPointsAtMeEvent(self, event):
        # we append the instance methods to the
        # event lists

        self.pointsAtMe.append(event)
    def raiseArmRaiseEvent(self):
        # iterating through the lists we call
        # each of the instance methods
        for i in self.armsRaise:
            i("Arms Raised")
    def raisePointsAtMeEvent(self):
        # iterating through the lists we call

        # each of the instance methods
        for i in self.pointsAtMe:
            i("Points at me")
    def raiseArms(self):
        self.raiseArmRaiseEvent()
    def pointAtMusician(self):
        self.raisePointsAtMeEvent()


# class that reacts to events
class Musician(object):
    def __init__(self, name):
        self.name = name
    def receiveEvent(self, msg):
        if msg == "Arms Raised":
            print self.name + " hold up instrument"

        if msg == "Points at me":
            print self.name + " play instrument"

# players

o = Orchestrator()
m = Musician("trumpet")
m2 = Musician("clarinet")

# Subscribe to the Orchestrator events:
# We're really just assigning instance methods
# of our Musician objects to the Orchestra object.

o.subscribeToArmRaiseEvent(m.receiveEvent)
o.subscribeToPointsAtMeEvent(m.receiveEvent)
o.subscribeToArmRaiseEvent(m2.receiveEvent)
o.subscribeToPointsAtMeEvent(m2.receiveEvent)

# Concert begins
o.raiseArms()
# ... other actions and events
# represented by:
print "do bee doo be dooo be do do do"

time.sleep(4)
# finally gets to your part of the song
o.pointAtMusician()

# my output:
#   trumpet hold up instrument
#   clarinet hold up instrument

#   do bee doo be dooo be do do do
#   trumpet play instrument
#   clarinet play instrument