Re: [Tutor] dollarize.py
> dollarize(1234567.8901) returns-> $1,234,567,89 >: > amount = raw_input("Enter an amount: ") > dollar_amount = dollarize(amount) > print dollar_amount the solution you're creating is *slightly* different than the original spec in the problem (Exercise 13-3). the argument to dollarize() is supposed to be a *float*, not a string. other than that, you're well on your way! also, be aware of the typo in the class skeleton provided on p. 619. the published changed the "`"s to "'"s on line 13. since the backtick quotes are going away in Python 3, i would just suggest changing "return `self.value`" to "return repr(self.value)". aside from this, the way i usually solve this problem is to save off the sign, round off the fraction/pennies, and then break it up into dollars and cents, then process the commas into the dollar amount, and finally merge everything back together with the sign and the $. best of luck! -- wesley ps. marty's use of locale is a great add-on to this problem. i've had some students go this distance and implement it in a similar way but not very often. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File Stream Assignment?
On: Friday, June 20, 2008 11:47 PM Kent Johnson Wrote: On Fri, Jun 20, 2008 at 5:47 PM, FT <[EMAIL PROTECTED]> wrote: >I would like to know how a file can be open for a stream event? What is a stream event? >I ask this question because of the SAPI 5 save a wave file and the only > way to do that is with a file stream. The file read is simple and uses the > isfilename flag, but the save file I can not find in all my searches, at > least for python. I have no idea what you are talking about. Kent Kent, This is what I got from the Microsoft SAPI web site. They have only code for C and VB and below is the VB version. I am trying to figure out where the stram gets assigned to the speak method for SAPI so a file can be saved. The following code illustrates how to speak a text file in a specific voice in Visual Basic. This example assumes a text file (ttstemp.txt) containing the text to be spoken already exists. ISpeechVoice.SpeakStream is used here to speak an SpFileStream that has been bound to the file. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create SAPI voice Set Voice = New SpVoice 'Assume that ttstemp.txt exists FileName = "c:\ttstemp.txt" 'Open the text file FileStream.Open FileName, SSFMOpenForRead, True 'Select Microsoft Sam voice Set Voice.voice = voice.GetVoices("Name=Microsoft Sam", "Language=409").Item(0) 'Speak the file stream Voice.SpeakStream FileStream 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing So, in this example it assigns a file stream to the file opened then connects to the SAPI Speak method to save it. But when I do that like they did above I get only the data spoken and the file with 0 bytes in it. I have tried looking everywhere for the file stream connection and can not seem to find the method to do so. Bruce ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File Stream Assignment?
"FT" <[EMAIL PROTECTED]> wrote Caveat: I know nothing about MS SAPI. The following code illustrates how to speak a text file in a specific voice in Visual Basic. This example assumes a text file (ttstemp.txt) containing the text to be spoken already exists. ISpeechVoice.SpeakStream is used here to speak an SpFileStream that has been bound to the file. Notice this says nothing about writing to a file. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create SAPI voice Set Voice = New SpVoice 'Assume that ttstemp.txt exists FileName = "c:\ttstemp.txt" 'Open the text file FileStream.Open FileName, SSFMOpenForRead, True 'Select Microsoft Sam voice Set Voice.voice = voice.GetVoices("Name=Microsoft Sam", "Language=409").Item(0) 'Speak the file stream Voice.SpeakStream FileStream 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing And the code nowhere writes to a file. The only file mentioned is the one read. So, in this example it assigns a file stream to the file opened then connects to the SAPI Speak method to save it. No, it calls the Speak method to speak it. It never saves anything so far as I can see. did above I get only the data spoken and the file with 0 bytes in it. I'm not sure which file has zero bytes. I hope not the one being spoken! But it sounds to me like your code is doing what the VB code does. I have tried looking everywhere for the file stream connection and can not seem to find the method to do so. I have no idea what you mean by this. Where are you looking? This is a COM object which is in the MS library. You will need to access it via PythonWin or ctypes or a Python wrapper of some sort. But the fact you are getting it to speak suggests you have succeeded in that already. I'm confused about why you think it should be saving anything? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File Stream Assignment?
Alan Gauld Wrote: "FT" <[EMAIL PROTECTED]> wrote Caveat: I know nothing about MS SAPI. > The following code illustrates how to speak a text file > in a specific voice in Visual Basic. This example Notice this says nothing about writing to a file. > Dim FileName As String > Dim FileStream As New SpFileStream > Dim Voice As SpVoice > 'Create SAPI voice And the code nowhere writes to a file. The only file mentioned is the one read. No, it calls the Speak method to speak it. It never saves anything so far as I can see. > did above I get only the data spoken and the file with 0 bytes in > it. I'm not sure which file has zero bytes. I hope not the one being spoken! But it sounds to me like your code is doing what the VB code does. I'm confused about why you think it should be saving anything? -- Alan Gauld Author of the Learn to Program web site Alan, Sorry about that, I copied over to quickly and actually took the example just below the one I wanted. This is the example and of course I looked back after sending it and discovered the very same conclusion you came up with. Below is the one I am talking about. How to connect the audio stream to an open file for writing is what I am trying to do. Speak to a wav file in automation The following example is written in Visual Basic. It has the same functionality as the above in C++. After the creation of an SpFileStream object, a default format, SAFT22kHz16BitMono, is assigned to the object so that user does not need to explicitly assign a wav format to it unless a specific wav format is needed. In this example, ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the FileStream to the file. The third parameter of ISpeechFileStream.Open is the Boolean, DoEvents. The default of this parameter is set to False. However, the user should always set it to True to display SAPI events while playing back the wav file. If the parameter is set to False, no engine events will be stored in the file, resulting in that no engine events will be fired during the wav file play back. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create a SAPI voice Set Voice = New SpVoice 'The output audio data will be saved to ttstemp.wav file FileName = "c:\ttstemp.wav" 'Create a file; set DoEvents=True so TTS events will be saved to the file FileStream.Open FileName, SSFMCreateForWrite, True 'Set the output to the FileStream Set Voice.AudioOutputStream = FileStream 'Speak the text Voice.Speak "hello world" 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File Stream Assignment?
Alan, This is what I wrote in python. The onlyu thing I did not do is a declaration of a filestream as the VB example does. I get no errors, just the Speak method just speaks. The saved file has no data, 0 Bytes. Now the note they mentioned was the True flag and I inserted that. import Sapi5, time, os av = Sapi5.SynthDriver() av.init()#AN ASSIGNMENT I COULD PLACE IN FIRST CALL AND CALL THE METHOD .Create() SYNC = av._sync ASYNC = av._async PURGE = av._purge ISFILE = av._is_filename XML = av._xml NOT_XML = av._not_xml PERSIST = av._persist_xml PUNC = av._punc WAIT = av._wait av.Speak("Hello!") av.Speak( "I am speaking in the default voice!") av.Speak( "Number of voices is: %d" % av.getVoiceCount()) av.Speak( "Hello! Now saying the punctuation in this sentence.", PUNC) time.sleep(.5) file4tts = open('test.wav', 'w', True) av.AudioOutputStream = file4tts av.Speak( "Hello World!", ASYNC) file4tts.close Microsoft Example: Speak to a wav file in automation The following example is written in Visual Basic. It has the same functionality as the above in C++. After the creation of an SpFileStream object, a default format, SAFT22kHz16BitMono, is assigned to the object so that user does not need to explicitly assign a wav format to it unless a specific wav format is needed. In this example, ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the FileStream to the file. The third parameter of ISpeechFileStream.Open is the Boolean, DoEvents. The default of this parameter is set to False. However, the user should always set it to True to display SAPI events while playing back the wav file. If the parameter is set to False, no engine events will be stored in the file, resulting in that no engine events will be fired during the wav file play back. Dim FileName As String Dim FileStream As New SpFileStream Dim Voice As SpVoice 'Create a SAPI voice Set Voice = New SpVoice 'The output audio data will be saved to ttstemp.wav file FileName = "c:\ttstemp.wav" 'Create a file; set DoEvents=True so TTS events will be saved to the file FileStream.Open FileName, SSFMCreateForWrite, True 'Set the output to the FileStream Set Voice.AudioOutputStream = FileStream 'Speak the text Voice.Speak "hello world" 'Close the Stream FileStream.Close 'Release the objects Set FileStream = Nothing Set Voice = Nothing ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File Stream Assignment?
"FT" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Alan, This is what I wrote in python. file4tts = open('test.wav', 'w', True) av.AudioOutputStream = file4tts av.Speak( "Hello World!", ASYNC) file4tts.close You need parentheses after close. Otherwise you are evaluating the function not executing it. Without closing the file thre is a possibility that the buffer is not being flushed to disk. But it could be a typo in which case I don't know what the problem is! :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File Stream Assignment?
Alan Gauld Wrote: "FT" <[EMAIL PROTECTED]> wrote Caveat: I know nothing about MS SAPI. > The following code illustrates how to speak a text file > in a specific voice in Visual Basic. This example assumes > a text file (ttstemp.txt) containing the text to be spoken > already exists. ISpeechVoice.SpeakStream is used here > to speak an SpFileStream that > has been bound to the file. Snip I have no idea what you mean by this. Where are you looking? This is a COM object which is in the MS library. You will need to access it via PythonWin or ctypes or a Python wrapper of some sort. But the fact you are getting it to speak suggests you have succeeded in that already. I'm confused about why you think it should be saving anything? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld Hi Alan, I did a search and I think it was about the 30'th search or more and finally came out with the exact code. Interesting enough it was on the win32 site and a person did not want to use the working code for something more like I was originally searching for, but it works. Below is the method I placed it into. I use the same Create function but the added feature is the lib and it was inside the Create assignment itself. You were correct in it needed to be in the com stuff. I do not know all that I need to know about this for there is so much to search and read to tie it all together. So I do it one piece at a time. I also used the same naming convention as the built in Speak method and I did not have to use C code to get it runnhing, instead used the same imports I already had. I attached the complete speech class module I am developing and the methods I am using at the moment. Here is the method: from comtypes.client import CreateObject #NEEDED IF THIS METHOD IS A STAND ALONE! #SET AUDIO STREAM FOR OUTPUT TO A FILE! def SpeakToWav(self, filename, text): """THIS METHOD ASSUMES THE IMPORT OF COMTYPES.CLIENT createObject SO A VOICE AND FILE STREAM OBJECT ARE CREATED WITH THE PASSING IN OF THE FILE NAME TO SAVE THE VOICE INTO AND THE TEXT DATA TO SPEAK AND STORE ONCE THE TEXT IS SPOKEN INTO THE FILE IT IS CLOSED AND THE OBJECTS DESTROYED!""" stream = CreateObject("SAPI.SpFileStream") tts4file = CreateObject( 'sapi.SPVoice') from comtypes.gen import SpeechLib stream.Open( filename, SpeechLib.SSFMCreateForWrite) tts4file.AudioOutputStream = stream tts4file.Speak( text, 0) stream.Close() del tts4file del stream #DRIVERS FOR SAPI 5 AND VOICES! #NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES. from comtypes.client import CreateObject import _winreg class constants4tts: Wait = -1 Sync = 0 Async = 1 Purge = 2 Is_filename = 4 XML = 8 Not_XML = 16 Persist = 32 Punc = 64 class SynthDriver(): name="sapi5" description="Microsoft Speech API version 5 (sapi.SPVoice)" _pitch = 0 _voices = [] _wait = -1 #WAIT INDEFINITELY _sync = 0 #WAIT UNTIL SPEECH IS DONE. _async = 1 #DO NOT WAIT FOR SPEECH _purge = 2 #CLEAR SPEAKING BUFFER _is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE _xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER. _not_xml = 16 #NO XML COMMANDS _persist_xml = 32 #Changes made in one speak command persist to other calls to Speak. _punc = 64 #PRONOUNCE ALL PUNCTUATION! def check(self): try: r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice") r.Close() return True except: return False #INITIALIZE ENGINE! def init(self): try: self.tts = CreateObject( 'sapi.SPVoice') self._voice=1 self._voiceCount = len(self.tts.GetVoices()) for v in range(self._voiceCount): self._voices.append( self.tts.GetVoices()[v]) return True except: return False #TERMINATE INSTANCE OF ENGINE! def terminate(self): del self.tts #NUMBER OF VOICES FOR ENGINE! def getVoiceCount(self): return len(self.tts.GetVoices()) #NAME OF A VOICE NUMBER! def getVoiceName(self, num): return self.tts.GetVoices()[num-1].GetDescription() #WHAT IS VOICE RATE? def getRate(self): "MICROSOFT SAPI 5 RATE IS -10 TO 10" return (self.tts.rate) #WHAT IS THE VOICE PITCH? def getPitch(self): "PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!" return self._pitch #GET THE ENGINE VOLUME! def getVolume(self): "MICROSOFT SAPI 5 VOLUME IS 1% TO 100%" return self.tts.volume #GET THE VOICE NUMBER! def getVoiceNum(self): return self._voice #SET A VOICE BY NAME! def setVoiceByName(self, name): "VOICE IS SET BY NAME!" for i in range( self._voiceCount): vp = self.tts.GetVoice
[Tutor] WIn32 extension -= exposing methods with a windows handle
I would like to capture information from a multi-player internet game in order to tabulate player statistics. Specifically, I need information from a chat box within the main play window. Using the win32 extension (win32gui module: EnumWindows, EnumChildWIndows) I can obtain a handle to the chat box. At that point, I don't see any apparent win32 functions to expose the methods available in the chat box and, thereby, extract the chat text information I need. So, if I have the handle to a child window, does anyone know how to enumerate the attributes and methods for that window using Python or its extensions? (Since the window is not a Python generated window, __dict__ doesn't work, or I am incorrectly using it: w = CreateWindowFromHandle(hwnd); print w.__dict__). Also, if I know that a particular method is supported by the window's class (e.g., GetText), can I use the window's handle to access the method (i.e., text = hwnd.GetText) ? Or, what is the correct syntax? Thanks for your help. Mike___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] WIn32 extension -= exposing methods with a windows handle
"Mike Meisner" <[EMAIL PROTECTED]> wrote i obtain a handle to the chat box. At that point, I don't see any apparent win32 functions to expose the methods available in the chat box and, thereby, extract the chat text information I need. It depends on the exact type of the dialog box. You can get the list of methods in the Pythonwin documentation, based on the Win32 API help. (Since the window is not a Python generated window, __dict__ doesn't work, or I am incorrectly using it: w = CreateWindowFromHandle(hwnd); print w.__dict__). Thats the right way to get a Python variable referencing it. Also, if I know that a particular method is supported by the window's class (e.g., GetText), can I use the window's handle to access the method (i.e., text = hwnd.GetText) ? No, you need to do what you did above and get a variable referencing the object so you could do w.GetText() - except I don't see GetText as a method of any Windows object I've looked at. Do you know what kind of Window object it is? The object browser in Pytonwin might be able to tell you... but I've never used it so don't really know!! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter on OS X
I've been writing a simple Tkinter interface to one of my programs. But it looks rather bad on OS X leopard. I was wondering why that was the case, since it seemed to take up at least some GUI elements (like button styles). I then came upon the following page: http://developer.apple.com/unix/toolkits.html that says that the Aqua version of Tk hasn't been integrated with Tkinter. Is this correct? Is there another way to write a front-end that looks more like a native app. I put a screenshot of my current UI up on my blog. http://bytebaker.com/2008/06/21/cocoa-python-and-the-quest-for-platform-independence/ -- The ByteBaker : http://www.bytebaker.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter on OS X
On Sat, Jun 21, 2008 at 5:55 PM, Shrutarshi Basu <[EMAIL PROTECTED]> wrote: > I've been writing a simple Tkinter interface to one of my programs. > But it looks rather bad on OS X leopard. I was wondering why that was > the case, since it seemed to take up at least some GUI elements (like > button styles). I then came upon the following page: > http://developer.apple.com/unix/toolkits.html I'm pretty sure that page is out-of-date, Tkinter does not require X11, it is integrated with Aqua. > that says that the Aqua version of Tk hasn't been integrated with > Tkinter. Is this correct? Is there another way to write a front-end > that looks more like a native app. Tkinter has a reputation as quick and ugly. Some dispute that and there may be ways to make it look better but if you are after good looks you might want to choose a different toolkit. wxPython, PyQt and PyGTK all have their proponents. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter on OS X
Shrutarshi Basu wrote: I've been writing a simple Tkinter interface to one of my programs. But it looks rather bad on OS X leopard. I was wondering why that was the case, since it seemed to take up at least some GUI elements (like button styles). I then came upon the following page: http://developer.apple.com/unix/toolkits.html that says that the Aqua version of Tk hasn't been integrated with Tkinter. Is this correct? Is there another way to write a front-end that looks more like a native app. I put a screenshot of my current UI up on my blog. http://bytebaker.com/2008/06/21/cocoa-python-and-the-quest-for-platform-independence/ Have you considered something like wx? That's a bit more heavyweight to develop to (but not a great deal), but it gives complete native look and feel on Unix, Windows and OSX. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Is this the right way to create a
I'm trying to create a library for the Last.fm webservice[1] and the first thing I created was a class for the Profile Information.[2] Is this the proper way of creating it? Is this useful to another programmer? import urllib import xml.etree.ElementTree as ET from BeautifulSoup import BeautifulStoneSoup as BSS BASEURL = 'http://ws.audioscrobbler.com/1.0/user/' class UserProfile(object): """Represents the user profile data""" def __init__(self, username): """Give the username""" self.username = username def getxmldata(self): url = BASEURL + self.username + '/profile.xml' self.xmldata = urllib.urlopen(url).read() def parsedata(self): soup = BSS(self.xmldata) self.url = soup.url.string self.realname = soup.realname.string self.sha1 = soup.mbox_sha1sum.string self.regdate = soup.registered.string self.unixregdate = soup.registered['unixtime'] self.age = soup.age.string self.gender = soup.gender.string self.country = soup.country.string self.playcount = soup.playcount.string self.avatar = soup.avatar.string self.icon = soup.icon.string self.id = soup.profile['id'] Also, how do I then begin to approach the whole API ? Do I create a User class the inherits from the UserProfile class and other classes for their Neighbours', Top Artists, etc ? Do a create a separate class for each web service ? I have never coded something like this before and all advice is welcome. [1] http://www.audioscrobbler.net/data/webservices/ [2] http://ws.audioscrobbler.com/1.0/user/RJ/profile.xml ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dollarize.py
Martin Walsh wrote: > def addcommas(f): > """ > This amounts to reversing everything left > of the decimal, grouping by 3s, joining > with commas, reversing and reassembling. > """ > # assumes type(f) == float > left, right = ('%0.2f' % f).split('.') > rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)] > return ','.join(rleft)[::-1] + '.' + right def addcommas(s): # assumes type(s)==str b=[] l=len(s) for i,v in enumerate(s): i+=1 # easier to understand w/ 1-based indexing, i think. b.append(v) if (l-i)%3==0 and not i==l: b.append(',') return ''.join(b) or, somewhat more tersely: def addcommas2(s): l=len(s) return ''.join(v+',' if (l-(i+1))%3==0 and not i+1-l==0 else v for i,v in enumerate(s)) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor