Python

Here’s a list of Python scripts that I have made, in the process of learning actual programming languages.  Also includes some cool links.

This page is mostly listed for my own benefit, should I need to write something and not be at my battlestation.  Please don’t just copy and paste (I’m sure these homework assignments will be in circulation for some time), but do give them a shot if you want to review the functions used.

 

Links

IDLE
The standard compiler for Python. Two seconds in Google to find but here’s a link.
IDLE

NLTK
Open-source toolkit for reading and working with the human language.  Wordnet is the lexical database addon.
Documentation – Interface – Wordnet Tutorial

 

Scripts

Seconds to Minutes and Hours, Input, Sentinel Loop


def main():

    #Prepare the variables
    iSeconds = 0
    tHours = 0
    tMinutes = 0
    
    #Introduction
    print("This program converts seconds into minutes and hours.\n")
    
    #Ask for input seconds
    iSeconds = input("Enter a number in seconds (Enter to quit) >> ")

    #Sentinel loop
    while iSeconds != "":

        #Eval the input
        tSeconds = eval(iSeconds)

        #Calculate the number of minutes
        tMinutes = tSeconds/60

        #Calculate the number of hours
        tHours = tSeconds/3600
        
        #Print result and ask for new input
        if (tMinutes == 1):
            print(tMinutes," Minute")
        else:
            print(tMinutes," Minutes")

        if (tHours == 1):
            print(tHours," Hour")
        else:
            print(tHours," Hours")

        iSeconds = input("\nEnter a number in seconds (Enter to quit) >> ")
    
    exit()


main()

Sum of Numbers From 1 to X, Sentinel, For X in Range


def main():

    #Prepare the variables
    total = 0
    sumAt = 0
    final = 0
    finalE = 0

    #What does this do?
    print('This program calculates the total sum of numbers.', end='\n')
    print('Ranging from 1 to n.  n can be any integer.', end='\n\n')
    
    #Ask for max number in range
    final = input('Enter a number for value n (Enter to quit) >> ')
    
    #Sentinel loop
    while final != "":

        #Flush the variables
        total = 0
        sumAt = 0

        #Eval
        finalE = eval(final)

        
        #Repeat through numbers in the range and add to total
        for x in range(0,finalE+1):
            sumAt = x
            total = total + sumAt
        

        #Print the result
        print('The sum of numbers 1 to ',finalE,' is ',total, end='\n\n')

        #Ask for max number in range
        final = input('Enter a number for value n (Enter to quit) >> ')

    #Close
    exit()


main()

Basic Graphic Shapes, import Graphics


import graphics
from graphics import *

def main():

    # Create the graphics window
    win = GraphWin('Herp derp',500,500)
    win.setBackground('purple')

    # Make a circle
    circ1 = Circle(Point(50,50), 40)
    circ1.setFill('red')
    circ1.setOutline('blue')
    circ1.draw(win)

    # Make a polgyon
    p1 = Point(115,40)
    p2 = Point(150,7)
    p3 = Point(190,30)
    p4 = Point(170,60)
    p5 = Point(160,35)
    p6 = Point(140,90)
    poly1 = Polygon(p1,p2,p3,p4,p5,p6)
    poly1.setFill('cyan')
    poly1.setOutline('orange')
    poly1.draw(win)

    # Draw some text
    Text(Point(120,120), 'This is a caption').draw(win)
    Text(Point(140,140), 'Click on the screen four times').draw(win)

    # Get three mouse clicks
    p7 = win.getMouse()
    p7.draw(win)
    p8 = win.getMouse()
    p8.draw(win)
    p9 = win.getMouse()
    p9.draw(win)
    p10 = win.getMouse()
    p10.draw(win)

    #Draw a polygon using those four points
    poly2 = Polygon(p7,p8,p9,p10)
    poly2.setFill('green')
    poly2.setOutline('yellow')
    poly2.draw(win)

main()

List of Miles to Kilometers, Lists


def main():

    #The initial range
    iRange=range(10,60,10)

    #Other variables
    iList=list(iRange)
    nList=list(iRange)
    iLength=len(iList)
    print("Initial: ",iList)
    
    #Modify the new list
    for i in range(0,iLength):
        
        #Do the deeps
        nList[i]=iList[i]*1.609344
        nList[i]=round(nList[i],3)

    #Print the new list
    print("Result: ",nList)
	
main()

Sum of Sequence of Fractions, Lists


def main():

    #The initial range
    iRange=range(10,60,10)

    #Other variables
    iList=list(iRange)
    nList=list(iRange)
    iLength=len(iList)
    print("Initial: ",iList)
    
    #Modify the new list
    for i in range(0,iLength):
        
        #Do the deeps
        nList[i]=iList[i]*1.609344
        nList[i]=round(nList[i],3)

    #Print the new list
    print("Result: ",nList)
	
main()

Percentile Score to Letter Grade, While Loop, Lists, import Math


import math

def main():

    #Prepare the variables
    iGrade=""
    eGrade=0
    fGrade=0
    Grades = ["F", "D", "C", "B", "A", "A"]

    #Introduction
    print("This program converts a 100 point exam to a letter grading.\n")
    
    #Ask for input seconds
    iGrade = input("Enter a number from 0 to 100 (Enter to quit) >> ")

    #Sentinel loop
    while iGrade != "":

        #Eval the input
        eGrade = eval(iGrade)

        #If the input is a valid score
        if (eGrade<=100) and (eGrade>=0):

            #Reduce the grade to 0-4
            fGrade = math.floor(((eGrade-50)/10))
            fGrade = max(fGrade,0)

            #IfPrint the letter grade
            print("Grade: ",Grades[fGrade],"\n")

        
        #Ask for new input
        iGrade = input("Enter a number from 0 to 100 (Enter to quit) >> ")
    
    exit()


main()

Graph Drawer, Definitions, import Graphics, Enter when Done

from graphics import *

def drawBar(window, year, height):
    # Draw a bar in window starting at year with given height
    bar = Rectangle(Point(year,0), Point(year+1, height))
    bar.setFill("green")
    bar.setWidth(2)
    bar.draw(window)
    

def main():
    # Introduction
    print("This program plots the growth of a 10-year investment.")

    # Get principal and interest rate
    principal = eval(input("Enter the initial principal: "))
    apr = eval(input("Enter the annualized interest rate: "))

    # Create a graphics window with labels on the left edge
    win = GraphWin("Investment Growth Chart", 320, 240)
    win.setBackground("white")
    win.setCoords(-1.75, -200, 11.5, 10400)
    Text(Point(-1,0), ' 0.0K').draw(win)
    Text(Point(-1,2500), ' 2.5K').draw(win)
    Text(Point(-1,5000), ' 5.0K').draw(win)
    Text(Point(-1,7500), ' 7.5K').draw(win)
    Text(Point(-1,10000), '10.0K').draw(win)

    # Draw bar for initial year
    drawBar(win, 0, principal)
    # Draw a bar for each subsequent year
    for year in range(1,11):
        principal = principal * (1 + apr)
        drawBar(win, year, principal)

    # close window when done
    input("Press  to quit.")
    win.close()

main()

Draw Line and Label Midpoint, import Graphics


import graphics
from graphics import *

def main():

    # Initial variables
    p1 = 0
    p2 = 0
    d1 = 0
    d2 = 0
    d3 = 0
    lin = 0
    label = 0
    midLabel = 0
    mx = 0
    my = 0
    
    # Tell us what this program does
    print("This program draws a line between two points, with the")
    print("mid point labelled as such.  Both of the two points are")
    print("provided by the user.")

    # Create the graphics window
    win = GraphWin('Herp derp 2 electric boogaloo',400,400)
    win.setBackground('purple')

    # Draw the label
    label = Text(Point(150,10),"Click anywhere for first point")
    label.draw(win)
    
    # Get first point
    p1 = win.getMouse()
    d1 = Circle(Point(p1.getX(),p1.getY()),2)
    d1.setFill("black")
    d1.draw(win)
    label.setText("Click anywhere for the second point")

    # Get second point
    p2 = win.getMouse()
    d2 = Circle(Point(p2.getX(),p2.getY()),2)
    d2.setFill("black")
    d2.draw(win)
    label.setText("   ")

    # Draw the line
    lin=Line(Point(p1.getX(),p1.getY()),Point(p2.getX(),p2.getY()))
    lin.draw(win)

    # Draw the mid-point label
    mx = (p1.getX() + p2.getX())/2
    my = (p1.getY() + p2.getY())/2
    d3 = Circle(Point(mx,my),2)
    d3.setFill("black")
    d3.draw(win)
    midLabel = Text(Point(mx,my-20),"Mid: "+str(mx)+","+str(my))
    midLabel.draw(win)
    
    # Tell how to quit
    num = input("Press Enter to quit >> ")

    exit()

main()

Motif Finder, Reading Files, Counting Substrings


def main():

    # Initial variables
    my_file = open("motifFinding.txt", "r")
    my_data = my_file.read().split()
    myString = my_data[0]
    mySubstring = my_data[1]
    SubstringLen = len(mySubstring)
    data_size=len(myString)
    
    #print("Data string has",data_size,"characters")
    #print("Searching for instances of '",mySubstring,"'")
    
    motifLength = 0
    tcount = 0
    tarray = []

    # Loop through each character of the string
    # Then look at that slice of (char + length) of substring
    for x in range(0,data_size):
        if (myString[x:x+SubstringLen] == mySubstring):
            tcount += 1
            tarray.append(x+1)

    # Loop through the tarray and print the positions
    for x in range(0,tcount):
        print(tarray[x]," ", end="")
    print("")

    # Tell how to quit
    num = input("Press Enter to quit >> ")

    exit()

main()

Number of Substrings in String, Definitions, for X in range


def numcopies(myString,mySubstring):
    
    # Initial variables
    SubstringLen = len(mySubstring)
    data_size=len(myString)
    result = [0,0,mySubstring]
    
    # Loop through each character of the string
    # Then look at that slice of (char + length) of substring
    for x in range(0,data_size):
        if (myString[x:x+SubstringLen] == mySubstring):
            result[1] += 1

            if (result[0] == 0):
                result[0] = x

    return(result)


def main():
    result = numcopies("This is my string of values","m")

    # Print results
    print("The character '",result[2],"' was found ",result[1]," times", sep="")
    print("The index of the first occurence is",result[0])

    # Tell how to quit
    num = input("Press Enter to quit >> ")

    exit()

main()

NLTK 1


import nltk

# from nltk.tokenize import sent_tokenize, word_tokenize

from nltk.corpus import stopwords

from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer


# from nltk.stem import PorterStemmer





# stop words, removing useless words
def stop_words():

    example_sentence = "This is an example showing off stop word filtration."
    stop_words = set(stopwords.words("english"))

    words = word_tokenize(example_sentence)

    filtered_sentence = []
    for w in words:
        if w not in stop_words:
            filtered_sentence.append(w)

    print(filtered_sentence)
# stop_words()






# removes stem from words, not all that important
def stemming():
    ps = PorterStemmer()

    new_text = "It is very important to be pythonly while you are pythoning with python.  All pythoners have pythoned poorly at least once."

    words = word_tokenize(new_text)
    for w in words:
        print(ps.stem(w))
# stemming()






def part_of_speech_tagging():
    train_text = state_union.raw("2005-GWBush.txt")
    sample_text = state_union.raw("2006-GWBush.txt")
    custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
    tokenized = custom_sent_tokenizer.tokenize(sample_text)

    def process_content():
        try:
            for i in tokenized:
                words = nltk.word_tokenize(i)
                tagged = nltk.pos_tag(words)

                print(tagged)

        except Exception as e:
            print(str(e))


    process_content()

# part_of_speech_tagging():

NLTK 2


import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer

train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
tokenized = custom_sent_tokenizer.tokenize(sample_text)

def process_content():
    try:
        for i in tokenized[6:]:
            words = nltk.word_tokenize(i)
            tagged = nltk.pos_tag(words)

            namedEnt = nltk.ne_chunk(tagged)

            namedEnt.draw()

            # chunkGram = r"""Chunk: {<RB.?>*<VB.?>*+?}"""
##            chunkGram = r"""Chunk: {<.*>+}
##                                    }<VB.?|IN|DT|TO>+{"""
##
##            chunkParser = nltk.RegexpParser(chunkGram)
##            chunked = chunkParser.parse(tagged)
##
##            #print(chunked)
##            chunked.draw()

    except Exception as e:
        print(str(e))


process_content()