# 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
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Showing posts with label dict. Show all posts
Showing posts with label dict. Show all posts
Thursday, February 3, 2011
Python - Roman Numeral to Number Generator
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.
Saturday, October 3, 2009
Python - storing persistance objects in file with shelve
# The shelve module is used to store objects in a file. # You use the file like a glorified dict with key, value # pairs. import shelve # shelve python doc objList = [] filename = 'shelveFile.shelve' # open and or create the file file = shelve.open(filename) # Here is an example class we'll create # instances of and then store in the file class ExampleClass(object): def __init__(self): self.a = 0 self.b = 1 self.c = 2 self.k = 0 def getTotal(self): return self.a + self.b + self.c # create several instances for i in xrange(3): obj = ExampleClass() obj.k = i obj.a = i+1 obj.b = i+2 obj.c = i+3 objList.append(obj) # now add the objects to file object for i in objList: # keys are strings file[str(i.k)] = i # The sync command will explicitly # write changes to file file.sync() # Closing the object will also execute # the sync command file.close() # The file (and the 3 objects in it # are now saved. # Now we'll reopen and verify the data is there file2 = shelve.open(filename) # Iterate through and print out # the object attributes (to verify # they are the values we assigned previously) for i in file2.keys(): j = file2[str(i)] print "a,b,c,k = ", j.a, j.b, j.c, j.k #output: #a,b,c,k = 1 2 3 0 #a,b,c,k = 3 4 5 2 #a,b,c,k = 2 3 4 1 # You can edit these values. # Here will change all 'a' attributes to 7 for i in file2.keys(): # Take note of how these changes were made. # You cannot merely alter an attribute # like file2[str(i)].a = 7 (this will # not work). j = file2[str(i)] j.a = 7 file2[str(j.k)] = j # And verify that changes are made: for i in file2.keys(): j = file2[str(i)] print "a,b,c,k = ", j.a, j.b, j.c, j.k #output: #a,b,c,k = 7 2 3 0 #a,b,c,k = 7 4 5 2 #a,b,c,k = 7 3 4 1 # now close the shelve file so you can # use the data objects another day. file2.close()
Thursday, October 1, 2009
Python - printing complex objects with pretty printing
# Pretty printing (using the pprint module) transforms # python objects into human readable output. # # Use pprint when you need to display a complex # data structure to users. import string import pprint # pprint python doc d = {} for i in string.ascii_lowercase: d[i] = string.ascii_lowercase.replace(i, ' ') print "not useful output:" print d # output: # not useful output: # {'a': ' bcdefghijklmnopqrstuvwxyz', 'c': 'ab defghijklmnopqrstuvwxyz', 'b': # 'a cdefghijklmnopqrstuvwxyz', 'e': 'abcd fghijklmnopqrstuvwxyz', 'd': 'abc # efghijklmnopqrstuvwxyz', 'g': 'abcdef hijklmnopqrstuvwxyz', 'f': 'abcde ghij # klmnopqrstuvwxyz', 'i': 'abcdefgh jklmnopqrstuvwxyz', 'h': 'abcdefg ijklmnop # qrstuvwxyz', 'k': 'abcdefghij lmnopqrstuvwxyz', 'j': 'abcdefghi klmnopqrstuv # wxyz', 'm': 'abcdefghijkl nopqrstuvwxyz', 'l': 'abcdefghijk mnopqrstuvwxyz', # 'o': 'abcdefghijklmn pqrstuvwxyz', 'n': 'abcdefghijklm opqrstuvwxyz', 'q': ' # abcdefghijklmnop rstuvwxyz', 'p': 'abcdefghijklmno qrstuvwxyz', 's': 'abcdef # ghijklmnopqr tuvwxyz', 'r': 'abcdefghijklmnopq stuvwxyz', 'u': 'abcdefghijkl # mnopqrst vwxyz', 't': 'abcdefghijklmnopqrs uvwxyz', 'w': 'abcdefghijklmnopqr # stuv xyz', 'v': 'abcdefghijklmnopqrstu wxyz', 'y': 'abcdefghijklmnopqrstuvwx # z', 'x': 'abcdefghijklmnopqrstuvw yz', 'z': 'abcdefghijklmnopqrstuvwxy '} # # All the data is there but it is difficult to read. # You can use pprint (pretty print) to make things easy to read. pprint # formats python datastructures to be human readable. print "human readable output:" pprint.pprint(d, indent=4) # output: #human readable output: #{ 'a': ' bcdefghijklmnopqrstuvwxyz', # 'b': 'a cdefghijklmnopqrstuvwxyz', # 'c': 'ab defghijklmnopqrstuvwxyz', # 'd': 'abc efghijklmnopqrstuvwxyz', # 'e': 'abcd fghijklmnopqrstuvwxyz', # 'f': 'abcde ghijklmnopqrstuvwxyz', # 'g': 'abcdef hijklmnopqrstuvwxyz', # 'h': 'abcdefg ijklmnopqrstuvwxyz', # 'i': 'abcdefgh jklmnopqrstuvwxyz', # 'j': 'abcdefghi klmnopqrstuvwxyz', # 'k': 'abcdefghij lmnopqrstuvwxyz', # 'l': 'abcdefghijk mnopqrstuvwxyz', # 'm': 'abcdefghijkl nopqrstuvwxyz', # 'n': 'abcdefghijklm opqrstuvwxyz', # 'o': 'abcdefghijklmn pqrstuvwxyz', # 'p': 'abcdefghijklmno qrstuvwxyz', # 'q': 'abcdefghijklmnop rstuvwxyz', # 'r': 'abcdefghijklmnopq stuvwxyz', # 's': 'abcdefghijklmnopqr tuvwxyz', # 't': 'abcdefghijklmnopqrs uvwxyz', # 'u': 'abcdefghijklmnopqrst vwxyz', # 'v': 'abcdefghijklmnopqrstu wxyz', # 'w': 'abcdefghijklmnopqrstuv xyz', # 'x': 'abcdefghijklmnopqrstuvw yz', # 'y': 'abcdefghijklmnopqrstuvwx z', # 'z': 'abcdefghijklmnopqrstuvwxy '} # # Formatted in this fashion its easy to see what # data is being stored in the dict.
Labels:
dict,
pprint,
PrettyPrinter,
python,
string
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
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
Saturday, September 26, 2009
Python - sun image detector - outline objects in an image
The input:
Where oh where is the sun?
Where oh where is the sun?
from PIL import Image # find brightest region of image # and visually identify the region class TheOutliner(object): 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 if __name__ == "__main__": print "Start Process"; # assumes that the test.jpg is in the # working directory theFile = "four.jpg" theOutFile = "four.output.jpg" cbp = CollectBrightPoints() cbp.loadImage(theFile) cbp.collectBrightPoints() brightDict = cbp.brightDict drawer = TheOutliner() drawer.doEverything(theFile, brightDict, theOutFile) print "Process complete"
The output: The sun has been detected!
Monday, September 21, 2009
Python - browse the web with python
# retrieve the html from a web site
import urllib2
import urllib
# query string
# in this example these GET parameters don't
# do anything. They are just here to show
# off the urlencode() function
qs = {}
qs['q'] = "items to search for"
qs['i'] = 22
qs_values = urllib.urlencode(qs)
# append everything together
url = "http://www.example.com"
full_url = url + '?' + qs_values
print "my full url: %s" %(full_url)
# get the data from the web
data = urllib2.urlopen(full_url)
# data now has all the html/css/javascsript in it
for item in data:
print item
## output:
##my full url: http://www.example.com?q=items+to+search+for&i=22
##<HTML>
##
##<HEAD>
##
## <TITLE>Example Web Page</TITLE>
##
##</HEAD>
##
##<body>
##
##<p>You have reached this web page by typing "example.com",
##
##"example.net",
##
## or "example.org" into your web browser.</p>
##
##<p>These domain names are reserved for use in documentation and are not available
##
## for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC
##
## 2606</a>, Section 3.</p>
##
##</BODY>
##
##</HTML>
Thursday, September 17, 2009
printing options
# python has several options for printing out literals and variables# the following four print lines all produce the same result
name = "steve"
num = 623
d = {}
d["name"] = name
d["num"] = num
print "Hello " + name + " your number is " + str(num)
print "Hello", name, "your number is", num
print "Hello %s your number is %d" % (name, num)
print "Hello %(name)s your number is %(num)d" %d
output:Hello steve your number is 623
Hello steve your number is 623
Hello steve your number is 623
Hello steve your number is 623
Wednesday, July 8, 2009
python dict
# a dictionary is created with curly braces {}
>>> d = {}
>>> type(d)
# add key,value pairs to the dict
>>> d['adam'] = 123422
>>> d['barry'] = 234223
>>> d['charlie'] = 999322
>>> d
{'barry': 234223, 'adam': 123422, 'charlie': 999322}
# test whether keys are in a dict
>>> 'steve' in d
False
>>> 'barry' in d
True
# iterate through a dict's keys
>>> for k in d.iterkeys():
... print k
...
barry
adam
charlie
# get a key's value from the dict
>>> d.get(k)
999322
# iterate through keys and print out key, value
>>> for k in d.iterkeys():
... print k, " = ", d.get(k)
...
barry = 234223
adam = 123422
charlie = 999322
# more detailed info on python dict: http://docs.python.org/library/stdtypes.html#mapping-types-dict
Subscribe to:
Posts (Atom)



