| | |
Starting Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() | View First Unread |
How would you write a number (integer) using English words? Here is one way, and to keep it simple let's just use numbers from 1 to 999.
python Syntax (Toggle Plain Text)
# write a number from 1 to 999 in English words ones = ["", "one ","two ","three ","four ", "five ", "six ","seven ","eight ","nine "] tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ", "fifteen ","sixteen ","seventeen ","eighteen ","nineteen "] twenties = ["","","twenty ","thirty ","forty ", "fifty ","sixty ","seventy ","eighty ","ninety "] # your test number between 1 and 999 n = 123 # separate into ones, tens/twenties, hundreds b1 = n % 10 b2 = (n % 100)//10 b3 = (n % 1000)//100 print b1, b2, b3 # test, for n = 123 should show 3 2 1 # start with an empty string to build up nw = "" # no tens/twenties if b2 == 0: nw = ones[b1] + nw # we have tens elif b2 == 1: nw = tens[b1] + nw # we have twenties etc. elif b2 > 1: nw = twenties[b2] + ones[b1] + nw # we have hundreds if b3 > 0: nw = ones[b3] + "hundred " + nw print nw # test 123 --> one hundred twenty three
Last edited by vegaseat; Mar 12th, 2008 at 11:34 am. Reason: order
May 'the Google' be with you!
Just another word frequency program that shows you how to sort the output by frequency:
python Syntax (Toggle Plain Text)
# count words in a text and show the first ten items # by decreasing frequency using a list of tuples # sample text for testing (could come from a text file) text = """\ My name is Fred Flintstone and I am a famous TV star. I have as much authority as the Pope, I just don't have as many people who believe it. """ word_freq = {} word_list = text.split() for word in word_list: # word all lower case word = word.lower() # strip any trailing period or comma word = word.rstrip('.,') # build the dictionary count = word_freq.get(word, 0) word_freq[word] = count + 1 # create a list of (freq, word) tuples for sorting by frequency freq_list = [(freq, word) for word, freq in word_freq.items()] # sort the list by the first element in each tuple (default) freq_list.sort(reverse=True) print "The ten most frequent words are:" for n, tup in enumerate(freq_list): # print the first ten items if n < 10: freq, word = tup print freq, word """ my output --> The ten most frequent words are: 3 i 3 as 2 have 1 who 1 tv 1 the 1 star 1 pope 1 people 1 name """
Last edited by ZZucker; Mar 14th, 2008 at 1:23 pm.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Another word frequency program, but this time we want ot create a dictionary of provider:frequency pairs from a number of given email addresses:
python Syntax (Toggle Plain Text)
# count the frequency of providers from a number of given emails emails = """\ manolis@gmail.com giannis@gmail.com kostas@yahoo.com eirini@yahoo.com ssss@aol.com wertza@yahoo.gr xristhanthi@gmail.com """ # split into list of lines (individual email) lines = emails.split() provider_freq = {} for item in lines: # split each line item at the @ character user, provider = item.split('@') #print user, provider # test # build the dictionary count = provider_freq.get(provider, 0) provider_freq[provider] = count + 1 print provider_freq """ my output --> {'yahoo.com': 2, 'aol.com': 1, 'gmail.com': 3, 'yahoo.gr': 1} """
Last edited by ZZucker; Mar 14th, 2008 at 1:51 pm.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
If you just want to count the words, lines and characters in a text file, Python offers an elegant solution:
Thanks to bgeddy for his inspiring pseudo code.
python Syntax (Toggle Plain Text)
# find the number of lines, words and characters in a text file # these are the counters, start at zero number_lines = 0 number_words = 0 number_characters = 0 # pick a text file you have filename = 'my_text.txt' for line in file(filename): # update the counters number_lines += 1 number_words += len(line.split()) number_characters += len(line) print filename, 'has:' print number_lines, 'lines' print number_words, 'words' print number_characters, 'characters'
Last edited by ZZucker; Mar 15th, 2008 at 2:36 am.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Here is an example how to use Python25's new partial function in a Tkinter callback situation ...
python Syntax (Toggle Plain Text)
# a tiny Tkinter calculator showing the # use of the new Python25 partial function import Tkinter as tk from functools import partial # needs Python25 or higher def click(key): global memory if key == '=': # avoid division by integer if '/' in entry.get() and '.' not in entry.get(): entry.insert(tk.END, ".0") # guard against the bad guys abusing eval() str1 = "-+0123456789." if entry.get()[0] not in str1: entry.insert(tk.END, "first char not in " + str1) # here comes the calculation part try: result = eval(entry.get()) entry.insert(tk.END, " = " + str(result)) except: entry.insert(tk.END, "--> Error!") elif key == 'C': entry.delete(0, tk.END) # clear entry elif key == '->M': memory = entry.get() # extract the result if '=' in memory: ix = memory.find('=') memory = memory[ix+2:] root.title('M=' + memory) elif key == 'M->': entry.insert(tk.END, memory) elif key == 'neg': if '=' in entry.get(): entry.delete(0, tk.END) try: if entry.get()[0] == '-': entry.delete(0) else: entry.insert(0, '-') except IndexError: pass else: # previous calculation has been done, clear entry if '=' in entry.get(): entry.delete(0, tk.END) entry.insert(tk.END, key) root = tk.Tk() root.title("My Calculator PF") # this also shows the calculator's button layout btn_list = [ '7', '8', '9', '*', 'C', '4', '5', '6', '/', 'M->', '1', '2', '3', '-', '->M', '0', '.', '=', '+', 'neg' ] # create all buttons with a loop r = 1 c = 0 for b in btn_list: rel = 'ridge' cmd = partial(click, b) # function click and argument b tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c) c += 1 if c > 4: c = 0 r += 1 # use Entry widget for an editable display entry = tk.Entry(root, width=33, bg="yellow") entry.grid(row=0, column=0, columnspan=5) root.mainloop()
Last edited by vegaseat; Mar 17th, 2008 at 7:18 pm.
May 'the Google' be with you!
Just a short Python code to show you how to use module urllib and module re to extract information from the html code of a web page. In this case we want to find all the links contained in the html code ...
python Syntax (Toggle Plain Text)
# extract the links in a web page's html code import urllib import re def get_links(url): # connect to url fp = urllib.urlopen(url) # read html code html = fp.read() # use regex module re to extract links in the html code links = re.findall('..."((?:http|ftp)s?://.*?)"...', html) return links # use the url of a web page you know url = 'http://www.python.org' for link in get_links(url): print link """ my output --> http://www.w3.org/1999/xhtml http://www.python.org/channews.rdf http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss http://python-groups.blogspot.com/feeds/posts/default http://www.showmedo.com/latestVideoFeed/rss2.0?tag=python http://www.awaretek.com/python/index.xml ... ... http://www.swa.hpi.uni-potsdam.de/dls/dls08/ http://www.xs4all.com/ http://www.pollenation.net/ """
May 'the Google' be with you!
Python makes it easy to compare two files and check if they are equal or differ:
python Syntax (Toggle Plain Text)
# compare two files and check if they are equal # files can be binary or text based import filecmp # pick two files you want to compare ... file1 = "Boing1.wav" file2 = "Boing2.wav" if filecmp.cmp(file1, file2): print "Files %s and %s are identical" % (file1, file2) else: print "Files %s and %s differ!" % (file1, file2)
Should you find Irony, you can keep her!
A simple way to make a scrolling text ticker or marquee ...
python Syntax (Toggle Plain Text)
# using Tkinter to create a marquee/ticker # uses a display width of 20 characters # not superly smooth but good enough to read import Tkinter as tk import time root = tk.Tk() # width=width chars, height=lines text text = tk.Text(root, width=20, height=1, bg='yellow') text.pack() # use a proportional font to handle spaces correctly text.config(font=('courier', 24, 'bold')) s1 = "I was wondering how someone would go about making a scrolling ticker" # pad front and end with 20 spaces s2 = ' ' * 20 s = s2 + s1 + s2 for k in range(len(s)): # use string slicing to do the trick ticker_text = s[k:k+20] text.insert("1.1", ticker_text) root.update() # delay by 0.15 seconds time.sleep(0.15) root.mainloop()
May 'the Google' be with you!
Simple debugging using the Python debug module pdb:
You need to play with this a little to get familiar with the pdb debugger.
python Syntax (Toggle Plain Text)
# test the built-in Python Debugger (Pdb in the Python reference) # at the debugger's '(Pdb)' prompt you can type h for help or # more specifically use h step or h next import pdb #help('pdb') # once the '(Pdb)' prompt shows, you are in the debugger # and you can trace through by entering: # # next (or n) which goes line by line and does not get # into functions or into every iteration of a loop # # step (or s) which is more detailed and for instance # loops through an entire range() # # so use next to get where you want to be and then use step, # once you have all the details you need, use next again pdb.set_trace() # now you can test the following code ... def hasCap(s): """returns True if the string s contains a capital letter""" for num in range(65, 91): capLetter = chr(num) if capLetter in s: return True return False str1 = 'Only pick up strings without Capital letters!' str2 = 'only pick up strings without capital letters!' # test the function hasCap() if hasCap(str1): print "str1 has a capital letter" else: print "str1 has no capital letter" if hasCap(str2): print "str2 has a capital letter" else: print "str2 has no capital letter"
Last edited by sneekula; Apr 5th, 2008 at 12:33 pm.
No one died when Clinton lied.
Tkinter only displays gif and ppm images, to show the more popular jpg and png images you have to incorporate the Python image Library (PIL). Here is an example:
python Syntax (Toggle Plain Text)
# load and display an image with Tkinter # Tkinter only reads gif and ppm images # use Python Image Library (PIL) for other image formats # give Tkinter a namespace to avoid conflicts with PIL # (they both have class Image) PIL is free from: # http://www.pythonware.com/products/pil/index.htm import Tkinter as tk from PIL import Image, ImageTk root = tk.Tk() cv1 = tk.Canvas(root, width=500, height=500) cv1.pack(fill='both', expand='yes') # open a jpeg file into an image object # image should be in the source folder or give full path name image1 = Image.open("flowers.jpg") # convert image object to Tkinter PhotoImage object tkimage1 = ImageTk.PhotoImage(image1) # tk.NW anchors upper left corner of image # at canvas coordinates x=10, y=20 cv1.create_image(10, 20, image=tkimage1, anchor=tk.NW) root.mainloop()
No one died when Clinton lied.
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: Python login-logout-sending email
- Next Thread: try-except
Views: 89471 | Replies: 197
| Thread Tools | Search this Thread |
Tag cloud for code, hints, python, tricks, tutorial
7 10 access ada api arax beginner blogger blogging bug c++ code combo csv cx-freeze daniweb data database development dictionary digital dropdownlist editor error event exam examples excel file format function game gdata google gui html http images innovation input itunes java joomla linux list lists method microsoft module mvcmodel2 mysqldb net news obexftp parameters password php print problem program programming projects py2exe pygame python random recursive reuse reverse rss ruby script security server shebang shutdown skinning source sprite string syntax table text threading tkinter tutorial ubuntu url urllib urllib2 variable vb virus vista visual visualbasic6 web windows wxpython xml








