Starting Python

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply   View First Unread View First Unread

Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 947
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #121
Mar 12th, 2008
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.
  1. # write a number from 1 to 999 in English words
  2.  
  3. ones = ["", "one ","two ","three ","four ", "five ",
  4. "six ","seven ","eight ","nine "]
  5.  
  6. tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ",
  7. "fifteen ","sixteen ","seventeen ","eighteen ","nineteen "]
  8.  
  9. twenties = ["","","twenty ","thirty ","forty ",
  10. "fifty ","sixty ","seventy ","eighty ","ninety "]
  11.  
  12. # your test number between 1 and 999
  13. n = 123
  14.  
  15. # separate into ones, tens/twenties, hundreds
  16. b1 = n % 10
  17. b2 = (n % 100)//10
  18. b3 = (n % 1000)//100
  19.  
  20. print b1, b2, b3 # test, for n = 123 should show 3 2 1
  21.  
  22. # start with an empty string to build up
  23. nw = ""
  24. # no tens/twenties
  25. if b2 == 0:
  26. nw = ones[b1] + nw
  27. # we have tens
  28. elif b2 == 1:
  29. nw = tens[b1] + nw
  30. # we have twenties etc.
  31. elif b2 > 1:
  32. nw = twenties[b2] + ones[b1] + nw
  33. # we have hundreds
  34. if b3 > 0:
  35. nw = ones[b3] + "hundred " + nw
  36.  
  37. 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!
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
0
  #122
Mar 14th, 2008
Just another word frequency program that shows you how to sort the output by frequency:
  1. # count words in a text and show the first ten items
  2. # by decreasing frequency using a list of tuples
  3.  
  4. # sample text for testing (could come from a text file)
  5. text = """\
  6. My name is Fred Flintstone and I am a famous TV
  7. star. I have as much authority as the Pope, I
  8. just don't have as many people who believe it.
  9. """
  10.  
  11. word_freq = {}
  12.  
  13. word_list = text.split()
  14.  
  15. for word in word_list:
  16. # word all lower case
  17. word = word.lower()
  18. # strip any trailing period or comma
  19. word = word.rstrip('.,')
  20. # build the dictionary
  21. count = word_freq.get(word, 0)
  22. word_freq[word] = count + 1
  23.  
  24. # create a list of (freq, word) tuples for sorting by frequency
  25. freq_list = [(freq, word) for word, freq in word_freq.items()]
  26.  
  27. # sort the list by the first element in each tuple (default)
  28. freq_list.sort(reverse=True)
  29.  
  30. print "The ten most frequent words are:"
  31. for n, tup in enumerate(freq_list):
  32. # print the first ten items
  33. if n < 10:
  34. freq, word = tup
  35. print freq, word
  36.  
  37. """
  38. my output -->
  39. The ten most frequent words are:
  40. 3 i
  41. 3 as
  42. 2 have
  43. 1 who
  44. 1 tv
  45. 1 the
  46. 1 star
  47. 1 pope
  48. 1 people
  49. 1 name
  50. """
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.
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
1
  #123
Mar 14th, 2008
Another word frequency program, but this time we want ot create a dictionary of provider:frequency pairs from a number of given email addresses:
  1. # count the frequency of providers from a number of given emails
  2.  
  3. emails = """\
  4. manolis@gmail.com
  5. giannis@gmail.com
  6. kostas@yahoo.com
  7. eirini@yahoo.com
  8. ssss@aol.com
  9. wertza@yahoo.gr
  10. xristhanthi@gmail.com
  11. """
  12.  
  13. # split into list of lines (individual email)
  14. lines = emails.split()
  15.  
  16. provider_freq = {}
  17. for item in lines:
  18. # split each line item at the @ character
  19. user, provider = item.split('@')
  20. #print user, provider # test
  21. # build the dictionary
  22. count = provider_freq.get(provider, 0)
  23. provider_freq[provider] = count + 1
  24.  
  25. print provider_freq
  26.  
  27. """
  28. my output -->
  29. {'yahoo.com': 2, 'aol.com': 1, 'gmail.com': 3, 'yahoo.gr': 1}
  30. """
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.
Reply With Quote Quick reply to this message  
Join Date: Jan 2008
Posts: 666
Reputation: ZZucker is on a distinguished road 
Solved Threads: 38
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: Starting Python

 
1
  #124
Mar 15th, 2008
If you just want to count the words, lines and characters in a text file, Python offers an elegant solution:
  1. # find the number of lines, words and characters in a text file
  2.  
  3. # these are the counters, start at zero
  4. number_lines = 0
  5. number_words = 0
  6. number_characters = 0
  7.  
  8. # pick a text file you have
  9. filename = 'my_text.txt'
  10. for line in file(filename):
  11. # update the counters
  12. number_lines += 1
  13. number_words += len(line.split())
  14. number_characters += len(line)
  15.  
  16. print filename, 'has:'
  17. print number_lines, 'lines'
  18. print number_words, 'words'
  19. print number_characters, 'characters'
Thanks to bgeddy for his inspiring pseudo code.
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.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 947
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #125
Mar 17th, 2008
Here is an example how to use Python25's new partial function in a Tkinter callback situation ...
  1. # a tiny Tkinter calculator showing the
  2. # use of the new Python25 partial function
  3.  
  4. import Tkinter as tk
  5. from functools import partial # needs Python25 or higher
  6.  
  7. def click(key):
  8. global memory
  9. if key == '=':
  10. # avoid division by integer
  11. if '/' in entry.get() and '.' not in entry.get():
  12. entry.insert(tk.END, ".0")
  13. # guard against the bad guys abusing eval()
  14. str1 = "-+0123456789."
  15. if entry.get()[0] not in str1:
  16. entry.insert(tk.END, "first char not in " + str1)
  17. # here comes the calculation part
  18. try:
  19. result = eval(entry.get())
  20. entry.insert(tk.END, " = " + str(result))
  21. except:
  22. entry.insert(tk.END, "--> Error!")
  23. elif key == 'C':
  24. entry.delete(0, tk.END) # clear entry
  25. elif key == '->M':
  26. memory = entry.get()
  27. # extract the result
  28. if '=' in memory:
  29. ix = memory.find('=')
  30. memory = memory[ix+2:]
  31. root.title('M=' + memory)
  32. elif key == 'M->':
  33. entry.insert(tk.END, memory)
  34. elif key == 'neg':
  35. if '=' in entry.get():
  36. entry.delete(0, tk.END)
  37. try:
  38. if entry.get()[0] == '-':
  39. entry.delete(0)
  40. else:
  41. entry.insert(0, '-')
  42. except IndexError:
  43. pass
  44. else:
  45. # previous calculation has been done, clear entry
  46. if '=' in entry.get():
  47. entry.delete(0, tk.END)
  48. entry.insert(tk.END, key)
  49.  
  50. root = tk.Tk()
  51. root.title("My Calculator PF")
  52.  
  53. # this also shows the calculator's button layout
  54. btn_list = [
  55. '7', '8', '9', '*', 'C',
  56. '4', '5', '6', '/', 'M->',
  57. '1', '2', '3', '-', '->M',
  58. '0', '.', '=', '+', 'neg' ]
  59.  
  60. # create all buttons with a loop
  61. r = 1
  62. c = 0
  63. for b in btn_list:
  64. rel = 'ridge'
  65. cmd = partial(click, b) # function click and argument b
  66. tk.Button(root,text=b,width=5,relief=rel,command=cmd).grid(row=r,column=c)
  67. c += 1
  68. if c > 4:
  69. c = 0
  70. r += 1
  71.  
  72. # use Entry widget for an editable display
  73. entry = tk.Entry(root, width=33, bg="yellow")
  74. entry.grid(row=0, column=0, columnspan=5)
  75.  
  76. root.mainloop()
Last edited by vegaseat; Mar 17th, 2008 at 7:18 pm.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 947
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #126
Mar 21st, 2008
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 ...
  1. # extract the links in a web page's html code
  2.  
  3. import urllib
  4. import re
  5.  
  6. def get_links(url):
  7. # connect to url
  8. fp = urllib.urlopen(url)
  9. # read html code
  10. html = fp.read()
  11. # use regex module re to extract links in the html code
  12. links = re.findall('..."((?:http|ftp)s?://.*?)"...', html)
  13. return links
  14.  
  15. # use the url of a web page you know
  16. url = 'http://www.python.org'
  17. for link in get_links(url):
  18. print link
  19.  
  20. """
  21. my output -->
  22. http://www.w3.org/1999/xhtml
  23. http://www.python.org/channews.rdf
  24. http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss
  25. http://python-groups.blogspot.com/feeds/posts/default
  26. http://www.showmedo.com/latestVideoFeed/rss2.0?tag=python
  27. http://www.awaretek.com/python/index.xml
  28. ...
  29. ...
  30. http://www.swa.hpi.uni-potsdam.de/dls/dls08/
  31. http://www.xs4all.com/
  32. http://www.pollenation.net/
  33. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 138
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #127
Mar 27th, 2008
Python makes it easy to compare two files and check if they are equal or differ:
  1. # compare two files and check if they are equal
  2. # files can be binary or text based
  3.  
  4. import filecmp
  5.  
  6. # pick two files you want to compare ...
  7. file1 = "Boing1.wav"
  8. file2 = "Boing2.wav"
  9. if filecmp.cmp(file1, file2):
  10. print "Files %s and %s are identical" % (file1, file2)
  11. else:
  12. print "Files %s and %s differ!" % (file1, file2)
Should you find Irony, you can keep her!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 947
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #128
Mar 29th, 2008
A simple way to make a scrolling text ticker or marquee ...
  1. # using Tkinter to create a marquee/ticker
  2. # uses a display width of 20 characters
  3. # not superly smooth but good enough to read
  4.  
  5. import Tkinter as tk
  6. import time
  7.  
  8. root = tk.Tk()
  9.  
  10. # width=width chars, height=lines text
  11. text = tk.Text(root, width=20, height=1, bg='yellow')
  12. text.pack()
  13.  
  14. # use a proportional font to handle spaces correctly
  15. text.config(font=('courier', 24, 'bold'))
  16.  
  17. s1 = "I was wondering how someone would go about making a scrolling ticker"
  18.  
  19. # pad front and end with 20 spaces
  20. s2 = ' ' * 20
  21. s = s2 + s1 + s2
  22.  
  23. for k in range(len(s)):
  24. # use string slicing to do the trick
  25. ticker_text = s[k:k+20]
  26. text.insert("1.1", ticker_text)
  27. root.update()
  28. # delay by 0.15 seconds
  29. time.sleep(0.15)
  30.  
  31. root.mainloop()
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,297
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 178
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #129
Apr 5th, 2008
Simple debugging using the Python debug module pdb:
  1. # test the built-in Python Debugger (Pdb in the Python reference)
  2. # at the debugger's '(Pdb)' prompt you can type h for help or
  3. # more specifically use h step or h next
  4.  
  5. import pdb
  6.  
  7. #help('pdb')
  8.  
  9. # once the '(Pdb)' prompt shows, you are in the debugger
  10. # and you can trace through by entering:
  11. #
  12. # next (or n) which goes line by line and does not get
  13. # into functions or into every iteration of a loop
  14. #
  15. # step (or s) which is more detailed and for instance
  16. # loops through an entire range()
  17. #
  18. # so use next to get where you want to be and then use step,
  19. # once you have all the details you need, use next again
  20.  
  21. pdb.set_trace()
  22.  
  23. # now you can test the following code ...
  24.  
  25. def hasCap(s):
  26. """returns True if the string s contains a capital letter"""
  27. for num in range(65, 91):
  28. capLetter = chr(num)
  29. if capLetter in s:
  30. return True
  31. return False
  32.  
  33. str1 = 'Only pick up strings without Capital letters!'
  34. str2 = 'only pick up strings without capital letters!'
  35.  
  36. # test the function hasCap()
  37. if hasCap(str1):
  38. print "str1 has a capital letter"
  39. else:
  40. print "str1 has no capital letter"
  41.  
  42. if hasCap(str2):
  43. print "str2 has a capital letter"
  44. else:
  45. print "str2 has no capital letter"
You need to play with this a little to get familiar with the pdb debugger.
Last edited by sneekula; Apr 5th, 2008 at 12:33 pm.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,297
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 178
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #130
Apr 6th, 2008
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:
  1. # load and display an image with Tkinter
  2. # Tkinter only reads gif and ppm images
  3. # use Python Image Library (PIL) for other image formats
  4. # give Tkinter a namespace to avoid conflicts with PIL
  5. # (they both have class Image) PIL is free from:
  6. # http://www.pythonware.com/products/pil/index.htm
  7.  
  8. import Tkinter as tk
  9. from PIL import Image, ImageTk
  10.  
  11. root = tk.Tk()
  12. cv1 = tk.Canvas(root, width=500, height=500)
  13. cv1.pack(fill='both', expand='yes')
  14.  
  15. # open a jpeg file into an image object
  16. # image should be in the source folder or give full path name
  17. image1 = Image.open("flowers.jpg")
  18. # convert image object to Tkinter PhotoImage object
  19. tkimage1 = ImageTk.PhotoImage(image1)
  20.  
  21. # tk.NW anchors upper left corner of image
  22. # at canvas coordinates x=10, y=20
  23. cv1.create_image(10, 20, image=tkimage1, anchor=tk.NW)
  24.  
  25. root.mainloop()
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



Similar Threads
Other Threads in the Python Forum


Views: 89471 | Replies: 197
Thread Tools Search this Thread



Tag cloud for code, hints, python, tricks, tutorial
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC