Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

Thursday, February 3, 2011

Python - Roman Numeral to Number Generator

# Convert a roman numeral to a number. 
# 
# If you are interested in roman numerals check out my other post  
# python script that takes a number and generates a roman numeral 
# 
# For a life time of knowledge checkout: 
# http://en.wikipedia.org/wiki/Roman_numerals 
# 
 
 
 
def ConvertRomanNumeralToNumber(roman_numeral):
    number_result = 0
    
    roman_numerals = {
        1:"I", 4:"IV", 5:"V", 9:"IX",
        10:"X", 40:"XL", 50:"L",
        90:"XC", 100:"C", 400:"CD",
        500:"D", 900:"CM", 1000:"M"}
 
    # Iterate through the roman numerals.  But you see here that I sort them to 
    # get the largest string size first: "CD" comes before "I" 
    for numeral_value in sorted(roman_numerals,
                                key=lambda roman: len(roman_numerals[roman]),
                                reverse=True):
        keep_converting = True
        while keep_converting:            
            if roman_numeral.find(roman_numerals[numeral_value]) != -1:
                number_result += numeral_value
                roman_numeral = roman_numeral.replace(roman_numerals[numeral_value], "", 1)
            else:
                keep_converting = False
                
    return number_result
 
 
print(ConvertRomanNumeralToNumber("MCDXLIV"))
print(ConvertRomanNumeralToNumber("MMMDCCCLXXXVIII"))
print(ConvertRomanNumeralToNumber("MMMCMXCIX"))
 
# my output: 
#  1444 
#  3888 
#  3999 
 
 

Python - Roman Numeral Generator

# Convert a number to a roman numeral. 
# 
# If you are interested in roman numerals check out my other post to convert roman numerals back to numbers 
# python script that takes roman numerals and generates numbers. 
# 
# To increase your life time of knowledge read up on roman numerals: 
# http://en.wikipedia.org/wiki/Roman_numerals 
 
 
def ConvertNumberToRomanNumeral(number):
    roman_numeral_result = "" 
    
    # Roman numeral dict. Place approved roman numeral key:value pairs 
    # in the dict and they will be used. 
    roman_numerals = {
        1:"I", 4:"IV", 5:"V", 9:"IX",
        10:"X", 40:"XL", 50:"L",
        90:"XC", 100:"C", 400:"CD",
        500:"D", 900:"CM", 1000:"M"}
 
    # Iterate from highest to lowest through the roman numerals. 
    for numeral_value in sorted(roman_numerals.keys(), reverse=True):
 
        # Continue replacing large roman numerals while the number is 
        # high enough. 
        while (number >= numeral_value):
            # Build the Roman Numeral string. 
            roman_numeral_result += roman_numerals[numeral_value]
            # Decrease the working number by the roman numeral value just 
            # added to the roman numeral result. 
            number -= numeral_value
 
    return roman_numeral_result
 
 
print(ConvertNumberToRomanNumeral(1444))
print(ConvertNumberToRomanNumeral(3888))
print(ConvertNumberToRomanNumeral(3999))
 
# my output: 
#  MCDXLIV 
#  MMMDCCCLXXXVIII 
#  MMMCMXCIX 
 
 

Friday, October 15, 2010

Python - palindrome detector

# palindrome detector
#
# parse text and print out palindromes
 
 
# make a map to remove punctuation
punc = {" ":'', ",":'',
        ".":'', "!":'',
        "?":'', "'":'',
        '"':'', ':':'',
        '\n':''}
puncMap = str.maketrans(punc)
 
# determines whether given text is a palindrome
def isPalindrome(text):
    # change to all the same case
    text = text.lower()
    # remove punctuation
    text = text.translate(puncMap)
    # to count as a palindrome it must have
    # at least 2 valid characters
    if (len(text) < 2):
        return False
    # palindrome if it reads the same
    # front or backwards
    return text == text[::-1]
 
 
givenText = """
    Hi Mom, welcome. A man, a plan, a canal, panama. And 
    other text. 
    """
 
# first check the whole text
if (isPalindrome(givenText)):
    print("The entire text: '" + givenText.strip() + "' is a palindrome.")
 
# now check by sentence
for sentence in givenText.split('.'):
    if (isPalindrome(sentence)):
        print("The sentence: '" + sentence.strip() + "' is a palindrome.")
 
# now check every word
for word in givenText.split(' '):
    if (isPalindrome(word)):
        print("The word: '" + word.strip() + "' is a palindrome.")
 
# my output:
# The sentence: 'A man, a plan, a canal, panama' is a palindrome.
# The word: 'Mom,' is a palindrome.
 
    
 
 

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 
 
 

Wednesday, March 31, 2010

Python - insult generator

# negative reinforcement through insults

#
#
# Sometimes negative reinforcement is the way to go.
# For the times when you need a kick in the pants
# rather than a pat on the back I whipped up this

# insult generator.
# It will churn out more insults then you can shake
# a stick at.

import random

class insultGenerator(object):
    def __init__(self):
        # setup the lists of insult fodder

        self.nounList = ['loser',
                         'jerk',
                         'nerd',
                         'doodie head',
                         'butthead',
                         'bonehead',
                         'dunce',
                         'moron',
                         'nerf herder']
        self.adjectiveList = ['smelly',
                              'ugly',
                              'gimpy',
                              'slimy',
                              'crabby',
                              'scabby',
                              'scratchy']
        self.connectorList = ['are one',
                              'are the biggest',
                              'are becoming a']
    def getInsult(self):
        insult = "you"

        # connector phrase
        connector = random.randint(1, len(self.connectorList))
        insult += " " + self.connectorList[connector-1]

        # adjectives
        adjCount = random.randint(2,4)
        random.shuffle(self.adjectiveList)
        for i in xrange(0,adjCount):
            if i != 0:
                insult += ", "

            else:
                insult += " "
            insult += self.adjectiveList[i]

        # ending noun
        noun = random.randint(1,len(self.nounList))
        insult += " " + self.nounList[noun-1]
        return insult


# a little example to get some insults flowing
if __name__ == '__main__':
    ig = insultGenerator()
    print ig.getInsult()
    print ig.getInsult()
    print ig.getInsult()
    print ig.getInsult()



# my output:
#   you are one ugly, slimy, scabby loser
#   you are the biggest scabby, slimy nerd
#   you are becoming a scabby, ugly, gimpy butthead

#   you are one slimy, smelly, crabby bonehead



Monday, October 19, 2009

Python - quickly update urls in a web page

# update a webpages url references. 
# Your web page has a collection of images and you 
# want to update all the "folder1" references 
# to the new folder you've populated called "newfolder" 
 
# normally you would open the actual html file 
# and iterate through the file one line at a time 
# like in this post.  
 
# but for simplicity sake lets just use a multi line string 
# for the example 
theString = """ <img src="folder1/pic2324.jpg" /> 
<img src="folder1/pic2255.png" /> 
<img src="folder2/pic552.jpg" /> 
<img src="folder1/pica2f.jpg" /> 
 
""" 
 
# all you need is to iterate through the 
# file and replace 'folder1' with 'newfolder' 
for line in theString.split('\n'):
    line = line.replace("folder1/", "newfolder/")
    print line
 
#output: 
#     <img src="newfolder/pic2324.jpg" /> 
#    <img src="newfolder/pic2255.png" /> 
#    <img src="folder2/pic552.jpg" /> 
#    <img src="newfolder/pica2f.jpg" /> 
 

Sunday, October 4, 2009

Python - make your own class attributes iterable

# It can be useful to iterate through data contained 
# in your own custom objects. 
 
# Lets say you have your own class 
class ExampleClass(object):
    def __init__(self):
        self.objectList = []
        self.objectDict = {}
        self.maxItem = 100
        self.objectItem = "" 
    def iterateList(self):
        return self.objectList
    def addListItem(self, item):
        self.objectList.append(item)
    def addDictItem(self, item, value):
        self.objectDict[item] = value
 
 
# create an instance of the class 
# and lets use it's iterating methods 
ec = ExampleClass()
 
# add some example data 
for i in xrange(10):
    ec.addListItem(i)
    ec.addDictItem(i, str(i)+"'s value")
 
# now that we have data lets iterate 
# through the data 
for item in ec.iterateList():
    print item
 
#output: 
#    0 
#    1 
#    2 
#    3 
#    4 
#    5 
#    6 
#    7 
#    8 
#    9 
 
 
 

Saturday, October 3, 2009

Python - using sqlite3 module for persistant data

# The sqlite3 lets you create and use
# a database with just a file

import sqlite3
# more detailed python doc sqlite3 

import os
# in this example we get the current working dir path 

# Choose the file to use for the
# db and connect (create it)

conn = sqlite3.connect(os.path.abspath('.') + "tempdb")

# grab a cursor and we can create the db schema
c = conn.cursor()

# if you happen to run through this example a few times
# you may notice that the data is persistant.  For this example
# we'll ensure that we're starting from ground zero
# drop the database (if it exists)

c.execute('drop table if exists users')

# create a table
c.execute('create table users (name text, age text, email text)')

# insert data
c.execute("""insert into users values ('steve', '30', 'blah@blah.com')""")
c.execute("""insert into users values ('steve2', '32', 'blah@blah2.com')""")
c.execute("""insert into users values ('steve3', '33', 'blah@blah3.com')""")

#,
#                    ('steve II', '20', 'blah2@blah.com'),
#                    ('steve III', '10', 'blah3@blah.com')""")

# now lets select our data
c.execute('select * from users')

# iterate through the results with for each
for row in c:
    print row

# output:
#    (u'steve', u'30', u'blah@blah.com')
#    (u'steve2', u'32', u'blah@blah2.com')

#    (u'steve3', u'33', u'blah@blah3.com')




Wednesday, September 30, 2009

Python - using yaml for configuration files

import yaml
# checkout and download yaml for python 

# you should probably put this config in a seperate file
# but for this example it is just a multi-line string
yamlConfigFile = """
cars:
    car0:
        type: toyota
        hp: 129
        mpg:
            city: 30
            highway: 35
        cost: 15,000
    car1:
        type: gm
        hp: 225
        mpg:
            city: 20
            highway: 25
        cost: 20,000
    car2:
        type: chevy
        hp: 220
        mpg:
            city: 22
            highway: 24
        cost: 21,000
"""

# the yaml file will be converted to a dict
# for sub sections the dict will nest dicts
theDict = yaml.load(yamlConfigFile)
print theDict
# output (I added some tabs and what not so you
#           could see the nested dict structure):
# {'cars':
#    {'car2':
#        {'mpg': {'city': 22, 'highway': 24},
#        'hp': 220,
#        'cost': '21,000',
#        'type': 'chevy'},
#    'car0':
#        {'mpg': {'city': 30, 'highway': 35},
#        'hp': 129,
#        'cost': '15,000',
#        'type': 'toyota'},
#    'car1':
#        {'mpg': {'city': 20, 'highway': 25},
#        'hp': 225,
#        'cost': '20,000',
#        'type': 'gm'}
#    }
#}

# to list the car types (like car1, car2, etc
print theDict['cars'].keys()
# output:
# ['car2', 'car0', 'car1']

# to display the type and cost of the vehicles
for c in theDict['cars'].keys():
    print theDict['cars'][c]['type'], "cost:", theDict['cars'][c]['cost']

# output:
#    chevy cost: 21,000
#    toyota cost: 15,000
#    gm cost: 20,000

# update the cost of toyota
theDict['cars']['car0']['cost'] = '25,000'
# the update is now in the dict representation of the yaml file

# to dump the yaml dict back to a file
# or in our case a multi-line string use the dump command
# which you could write to a file
print yaml.dump(theDict)
# output:
#    cars:
#      car0:
#        cost: 25,000
#        hp: 129
#        mpg: {city: 30, highway: 35}
#        type: toyota
#      car1:
#        cost: 20,000
#        hp: 225
#        mpg: {city: 20, highway: 25}
#        type: gm
#      car2:
#        cost: 21,000
#        hp: 220
#        mpg: {city: 22, highway: 24}
#        type: chevy



Tuesday, September 29, 2009

Python - generate double dutch

# this example is similar 
# to the double dutch generator 
 
def createDoubleDutch(word):
    ''' 
        create and return a double 
        dutch version of word 
    ''' 
    for v in ("a", "e", "i", "o", "u", "y"):
        # double dutch-ize each vowel 
        word = word.replace(v, v+"b"+v)
    return word
 
if __name__ == '__main__':
    ddSentence = "" 
    for w in "My sample sentence for double dutch".split(' '):
           ddSentence += createDoubleDutch(w) + " " 
    print ddSentence.strip()
 
#output: 
# Myby sabamplebe sebentebencebe fobor doboubublebe dubutch 
 
 

Monday, September 28, 2009

Python - detect and label objects in images


Image to be analyzed


Detected Objects have now been outlined 
from PIL import Image

# you'll need to get PIL 
# some other (shorter) scripts
# that use PIL:
#   create a thumbnail with PIL  
#   find the average image RGB  
#   replace image colors with PIL  
#
# this script is based on the

#   find the sun script   

class TheOutliner(object):
    ''' takes a dict of xy points and
        draws a rectangle around them '''
    def __init__(self):
        self.outlineColor = 0, 255, 255
        self.pic = None
        self.picn = None
        self.minX = 0
        self.minY = 0
        self.maxX = 0
        self.maxY = 0
    def doEverything(self, imgPath, dictPoints, theoutfile):
        self.loadImage(imgPath)
        self.loadBrightPoints(dictPoints)
        self.drawBox()
        self.saveImg(theoutfile)
    def loadImage(self, imgPath):
        self.pic = Image.open(imgPath)
        self.picn = self.pic.load()
    def loadBrightPoints(self, dictPoints):
        '''iterate through all points and

           gather max/min x/y '''


        # an x from the pool (the max/min
        #   must be from dictPoints)
        self.minX = dictPoints.keys()[0][0]
        self.maxX = self.minX
        self.minY = dictPoints.keys()[0][1]
        self.maxY = self.minY


        for point in dictPoints.keys():
            if point[0] < self.minX:
                self.minX = point[0]
            elif point[0] > self.maxX:
                self.maxX = point[0]

            if point[1]< self.minY:
                self.minY = point[1]
            elif point[1] > self.maxY:
                self.maxY = point[1]
    def drawBox(self):
        # drop box around bright points

        for x in xrange(self.minX, self.maxX):
            # top bar
            self.picn[x, self.minY] = self.outlineColor
            # bottom bar
            self.picn[x, self.maxY] = self.outlineColor
        for y in xrange(self.minY, self.maxY):
            # left bar

            self.picn[self.minX, y] = self.outlineColor
            # right bar
            self.picn[self.maxX, y] = self.outlineColor
    def saveImg(self, theoutfile):
        self.pic.save(theoutfile, "JPEG")



#class CollectBrightPoints(object):
#
#    def __init__(self):

#        self.brightThreshold = 240, 240, 240
#        self.pic = None
#        self.picn = None
#        self.brightDict = {}
#    def loadImage(self, imgPath):
#        self.pic = Image.open(imgPath)
#        self.picn = self.pic.load()
#    def collectBrightPoints(self):
#        for x in xrange(self.pic.size[0]):

#            for y in xrange(self.pic.size[1]):
#                r,g,b = self.picn[x,y]
#                if r > self.brightThreshold[0] and \
#                    g > self.brightThreshold[1] and \
#                    b > self.brightThreshold[2]:
#                    # then it is brighter than our threshold

#                    self.brightDict[x,y] = r,g,b


class ObjectDetector(object):
    ''' returns a list of dicts representing 
        all the objects in the image '''
    def __init__(self):
        self.detail = 4
        self.objects = []
        self.size = 1000
        self.no = 255
        self.close = 100
        self.pic = None
        self.picn = None
        self.brightDict = {}
    def loadImage(self, imgPath):
        self.pic = Image.open(imgPath)
        self.picn = self.pic.load()
        self.picSize = self.pic.size
        self.detail = (self.picSize[0] + self.picSize[1])/2000
        self.size = (self.picSize[0] + self.picSize[1])/8
        # each must be at least 1 -- and the larger

        #   the self.detail is the faster the analyzation will be
        self.detail += 1
        self.size += 1
        
    def getSurroundingPoints(self, xy):
        ''' returns list of adjoining point '''
        x = xy[0]
        y = xy[1]
        plist = (
            (x-self.detail, y-self.detail), (x, y-self.detail), (x+self.detail, y-self.detail),
            (x-self.detail, y),(x+self.detail, y),
            (x-self.detail, y+self.detail),(x, y+self.detail),(x+self.detail,y+self.detail)
            )
        return (plist)

    def getRGBFor(self, x, y):
        try:
            return self.picn[x,y]
        except IndexError as e:
            return 255,255,255

    def readyToBeEvaluated(self, xy):
        try:
            r,g,b = self.picn[xy[0],xy[1]]
            if r==255 and g==255 and b==255:
                return False
        except:
            return False
        return True

    def markEvaluated(self, xy):
        try:
            self.picn[xy[0],xy[1]] = self.no, self.no, self.no
        except:
            pass

    def collectAllObjectPoints(self):
        for x in xrange(self.pic.size[0]):
            if x % self.detail == 0:
                for y in xrange(self.pic.size[1]):
                    if y % self.detail == 0:
                        r,g,b = self.picn[x,y]
                        if r == self.no and \
                            g == self.no and \
                            b == self.no:
                            # then no more

                            pass
                        else:
                            ol = {}
                            ol[x,y] = "go"
                            pp = []
                            pp.append((x,y))
                            stillLooking = True
                            while stillLooking:
                                if len(pp) > 0:
                                    xe, ye = pp.pop()
                                    # look for adjoining points

                                    for p in self.getSurroundingPoints((xe,ye)):
                                        if self.readyToBeEvaluated((p[0], p[1])):
                                            r2,g2,b2 = self.getRGBFor(p[0], p[1])
                                            if abs(r-r2) < self.close and \
                                                abs(g-g2) < self.close and \
                                                abs(b-b2) < self.close:
                                                # then its close enough

                                                ol[p[0],p[1]] = "go"
                                                pp.append((p[0],p[1]))

                                            self.markEvaluated((p[0],p[1]))
                                        self.markEvaluated((xe,ye))
                                else:
                                    # done expanding that point
                                    stillLooking = False
                                    if len(ol) > self.size:
                                        self.objects.append(ol)








if __name__ == "__main__":
    print "Start Process";

    # assumes that the .jpg files are in
    #   working directory 
    theFile = "3.jpg"

    theOutFile = "3.output.jpg"

    import os
    os.listdir('.')
    for f in os.listdir('.'):
        if f.find(".jpg") > 0:
            theFile = f
            print "working on " + theFile + "..."

            theOutFile = theFile + ".out.jpg"
            bbb = ObjectDetector()
            bbb.loadImage(theFile)
            print "     analyzing.."
            print "     file dimensions: " + str(bbb.picSize)
            print "        this files object weight: " + str(bbb.size)
            print "        this files analyzation detail: " + str(bbb.detail)
            bbb.collectAllObjectPoints()
            print "     objects detected: " +str(len(bbb.objects))
            drawer = TheOutliner()
            print "     loading and drawing rectangles.."

            drawer.loadImage(theFile)
            for o in bbb.objects:
                drawer.loadBrightPoints(o)
                drawer.drawBox()

            print "saving image..."
            drawer.saveImg(theOutFile)

            print "Process complete"

#output
#Start Process
#working on A Good Book to Have on Your Shelf.jpg...
#     analyzing..
#     file dimensions: (500, 667)
#        this files object weight: 146
#        this files analyzation detail: 1
#     objects detected: 6
#     loading and drawing rectangles..

#saving image...
#Process complete
#working on bamboo-forest.jpg...
#     analyzing..
#     file dimensions: (640, 480)
#        this files object weight: 141
#        this files analyzation detail: 1
#     objects detected: 68
#     loading and drawing rectangles..

#saving image...
#
# .............. SNIP .... (I had 20 jpeg files in the dir)
#
#working on Family_Photo.jpg...
#     analyzing..
#     file dimensions: (4200, 3300)
#        this files object weight: 938
#        this files analyzation detail: 4

#     objects detected: 20
#     loading and drawing rectangles..
#saving image...
#Process complete


Tuesday, September 15, 2009

Python - reorder a sentence alphabetically

# reorder the words in a sentence alphabetically


def sentenceAlphabetizer(sentence):
    words = sentence.split(' ')
    words.sort()
    sentence = ""
    for word in words:
        sentence += word + " "
    return sentence.strip()



if __name__ == '__main__':
    print sentenceAlphabetizer("basic applepie zoo party")

#output:
#   'applepie basic party zoo'