Re: [Tutor] What is this [] construction?
On Mon, Mar 2, 2009 at 11:18 PM, Andre Engels wrote: > On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson > wrote: > >self.recent_events = [ event for event in self.recent_events > >if os.path.exists(event) and > >(time.time() - os.path.getmtime(event)) < > > 3600.0 ] > In this example, we'll step through self.recent_events - which apparently is a list of filenames - and call each item we come across "event". That's the "for event in self.recent_events" part. If the filename corresponds to an actual file ("if os.path.exists(event)") AND that file has been modified less than an hour ago (the difference between the current time and the file's modification time is less than 3,600 seconds), then we add "event" to the list we're building and move on to the next "event" until we're done. At the end, we call our new list self.recent_events, which replaces the list we were looping through a moment ago. Chances are it's a bit shorter now. List comprehensions will make your head hurt the first few dozen times you encounter them. After that, they become easier to use than the longer for-loop structure they replace - as André pointed out, they read almost like English. -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Touchscreen GUI for PyKaraoke - Job in London
Hi, I am looking for someone to write a touchscreen GUI for PyKaraoke ( http://www.kibosh.org/pykaraoke/). Looking for someone based in or around London with a lot of experience of Python and Linux who willl be able to complete this project quickly. Knowledge of sound and video processing on Linux a bonus. Please contact me for further details. Thanks, Alex ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] animation with Tkinter canvas
Hello, I am attempting to make a simple animation of a vibrating string using Tkinter canvas. I haven't been able to find much information on how to do it. I have my data of position x on the string at time t. I can plot it with Tkinter showing the string for all times at once: width=1500 height=300 root = Tk() root.title("SinWave") canvas = Canvas(width=width,height=height,bg='white') linecoords=[] for i in range(mi): for j in range(ni): linecoords.append(width*x[j]) linecoords.append(height*(1/2+U[i,j])) canvas.create_line(linecoords,fill='black') root.update() canvas.pack() mainloop() Now I know that to get animation involves a root.update() and a root.update_idletasks() somewhere but I can't figure out how to use these! Thank you for your help. -Gerard. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] animation with Tkinter canvas
On Tue, Mar 3, 2009 at 3:05 AM, Mr Gerard Kelly wrote: > Hello, I am attempting to make a simple animation of a vibrating string using > Tkinter canvas. > I haven't been able to find much information on how to do it. > I have my data of position x on the string at time t. I can plot it > with > root.update() > > canvas.pack() > mainloop() > > > Now I know that to get animation involves a root.update() and a > root.update_idletasks() somewhere but I can't figure out how to use these! You don't have to use root.update. If you're drawing items on a canvas you can delete them later. 34: for x in xrange(0, 10): 35: y = c.create_line(0,0, x*x, x*x) 36: time.sleep(.5) 37: c.update_idletasks() #Force redraw 38: c.delete(y) Try those 5 lines and see if it works for you. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Shelve: remove dictionary from list
Hello all, I'm using the Shelve module to store dictionaries in a list as a value of a key. So: key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] The problem is I can't remove a dictionary from the list. import shelve s = shelve.open('file') try: for index, value in enumerate(s['key']): if value['keyA'] == 1 and value['keyB'] == 2: del value[index] finally: s.close() If I do some printing in between, I can see the dictionary actually gets removed, but doesn't get saved. Any ideas why? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shelve: remove dictionary from list
On Tue, Mar 3, 2009 at 12:18 PM, Timo wrote: > Hello all, I'm using the Shelve module to store dictionaries in a list as a > value of a key. > > So: > > key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}] > > The problem is I can't remove a dictionary from the list. > > > import shelve > > s = shelve.open('file') > try: > for index, value in enumerate(s['key']): > if value['keyA'] == 1 and value['keyB'] == 2: > del value[index] > finally: > s.close() > > > If I do some printing in between, I can see the dictionary actually gets > removed, but doesn't get saved. Any ideas why? >From the shelve docs: By default, mutations to persistent-dictionary mutable entries are not automatically written back. If the optional writeback parameter is set to True, all entries accessed are cached in memory, and written back at close time; this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated). In other words, by default, shelve does not know about changes you make to mutable values. You can either - open the shelve with writeback=True - explicitly store the modified value back into the shelve: key = s['key'] # modify key s['key'] = key s.close() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html I see my post of yesterday, "Maintaining the Same Variable Type--Tkinter", went over like a lead balloon. :-) (Note though the Myth Busters TV series successfully built and flew a lead balloon.) Let's see if I can really simplify what I'm after. I've pulled the essentials out of the original larger program I'm trying to modify. 2000 lines down to 80. I've only added a few lines of my own, and changed the menu and dialog content. Although I've heavily modified the original code to accept a config file, and set up variable to initialize the widgets, trying to bridge some code in the Enter_Data_Dialog and Set_Enter_Data objects control variable code is where the trouble lays for completing the modifications. The code below puts up a window with one menu and two submenus items, Enter Data, and Exit. Select Enter Data and put in an integer number. It all works fine. Basically, what I want to do is eliminate code like dialog.anumberVar.get() and replace it by constructing the appropriate names for the config file. In this case, the config file might contain: anumber = 123 Comments? BTW, the Quit function is original but doesn't kill the window when Quit is used. What fixes that? For more bonus points, it seems as though the try statement in the dialog should really bring up an "Error" dialog saying something is wrong, when an invalid entry occurs. No need to construct an error dialog for me, but I'd be curious how it might be handled. =fun-intVar.py=== from Tkinter import * import tkSimpleDialog import tkMessageBox class IntVar_GUI: def __init__(self, master): master.title('Control Variable Fun') self.frame = Frame(master,takefocus=1, highlightthickness=2, highlightcolor='blue') self.frame.configure(height=200,width=200) self.frame.pack() #self.frame.bind("", self.HandleKey) self.anumber = 123 # Want name and value to be configurable self.master = master menu = Menu(master) master.config(menu=menu) self.mainMenu = Menu(menu) menu.add_cascade(label="My Menu",menu=self.mainMenu) self.mainMenu.add_command(label="Enter Data", command=self.Set_Enter_Data) self.mainMenu.add_command(label="Exit",underline=1,command=self.Quit) self.Focus() def Set_Enter_Data(self): sdict = {} sdict[ "ok" ] = False sdict[ "anumber" ] = self.anumber dialog = Enter_Data_Dialog( self.master, sdict ) self.Focus() print "Howdy, set data. Number is:", dialog.anumberVar.get() print "dict:", dialog.sdict if not dialog.sdict["ok"]: return try: self.anumber = int(eval(dialog.anumberVar.get())) print "OK" except: print "Not OK" pass print "self.anumber:", self.anumber def Quit(self): self.running = False self.master.quit() def Focus( self ): self.frame.focus_set() class Enter_Data_Dialog(tkSimpleDialog.Dialog): def __init__(self, parent, sdict): self.sdict = sdict tkSimpleDialog.Dialog.__init__(self, parent) def body(self,master): self.title("Set a Number Entry Dialog") Label( master, text="Number ").grid(row=0, sticky=W) self.anumberVar = StringVar() entry = Entry(master, width=10, textvariable=self.anumberVar).grid(row=0, column=1) self.anumberVar.set( "%d" % self.sdict["anumber"] ) return entry def apply(self): self.sdict["ok"] = True def Process(): root = Tk() app = IntVar_GUI(root) root.mainloop() if __name__ == "__main__": Process() -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
On Tue, Mar 3, 2009 at 1:54 PM, Wayne Watson wrote: > > BTW, the Quit function is original but doesn't kill the window when Quit is > used. What fixes that? For more bonus points, it seems as though the try > statement in the dialog should really bring up an "Error" dialog saying > something is wrong, when an invalid entry occurs. No need to construct an > error dialog for me, but I'd be curious how it might be handled. > For the error dialog you can easily use tkMessageBox: just import tkMessageBox and then use this: In [2]: tkMessageBox.showerror('Some Error', 'An Error occurred!') Out[2]: 'ok' If you're expecting a specific error you can use try: #some statements except SpecificError: #Handle the error In this case (at least the block I looked at) it's just printing to the command line. You can handle it using any one of the message boxes or creating your own. > def Quit(self): > self.running = False > self.master.quit() > You could also try self.master.destroy() when I tried: from Tkinter import * root = Tk() root.quit() in an ipython session. It didn't close my root window but the destroy method did. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Difference in minutes between two time stamps
import datetime s = '09:35:23' datetime.datetime.strptime(s, '%H:%M:%S') datetime.datetime(1900, 1, 1, 9, 35, 23) Can you figure out how to proceed from there? In case she doesn't know: import datetime as dt start="09:35:23" end="10:23:00" start_dt = dt.datetime.strptime(start, '%H:%M:%S') end_dt = dt.datetime.strptime(end, '%H:%M:%S') diff.seconds/60 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Difference in minutes between two time stamps
import datetime s = '09:35:23' datetime.datetime.strptime(s, '%H:%M:%S') datetime.datetime(1900, 1, 1, 9, 35, 23) Can you figure out how to proceed from there? In case she doesn't know: import datetime as dt start="09:35:23" end="10:23:00" start_dt = dt.datetime.strptime(start, '%H:%M:%S') end_dt = dt.datetime.strptime(end, '%H:%M:%S') I forgot to paste in between: diff = (end_dt - start_dt) diff.seconds/60 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html WW, good. Thanks. destroy() took care of it, but I wonder what advantage there was to Quit()? WW W W wrote: On Tue, Mar 3, 2009 at 1:54 PM, Wayne Watson wrote: BTW, the Quit function is original but doesn't kill the window when Quit is used. What fixes that? For more bonus points, it seems as though the try statement in the dialog should really bring up an "Error" dialog saying something is wrong, when an invalid entry occurs. No need to construct an error dialog for me, but I'd be curious how it might be handled. For the error dialog you can easily use tkMessageBox: just import tkMessageBox and then use this: In [2]: tkMessageBox.showerror('Some Error', 'An Error occurred!') Out[2]: 'ok' If you're expecting a specific error you can use try: #some statements except SpecificError: #Handle the error In this case (at least the block I looked at) it's just printing to the command line. You can handle it using any one of the message boxes or creating your own. def Quit(self): self.running = False self.master.quit() You could also try self.master.destroy() when I tried: from Tkinter import * root = Tk() root.quit() in an ipython session. It didn't close my root window but the destroy method did. HTH, Wayne -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
"Wayne Watson" wrote see my post of yesterday, "Maintaining the Same Variable Type--Tkinter", went over like a lead balloon. :-) Yeah, I had no idea what you meant :-) I've heavily modified the original code to accept a config file, and set up variable to initialize the widgets, trying to bridge some code in the Enter_Data_Dialog and Set_Enter_Data objects control variable code is where the trouble lays Yep, and part of it is the attempt to create variables dynamically. It's so much easier if you use a dictionary or a list of name,value tuples. The code below puts up a window with one menu and two submenus items, Enter Data, and Exit. Select Enter Data and put in an integer number. It all works fine. It works with hard coded variable names. Trying to use dynamic variable names will be much trickier! Basically, what I want to do is eliminate code like dialog.anumberVar.get() and replace it by constructing the appropriate names for the config file. If you used a list of variables you could replace it with self.varList[0][1] = dialog.myVar.get() In this case, the config file might contain: anumber = 123 and you store that as varList.append( (varname, varValue) ) If there is only one variable at a time you could just use the tuple of course: self.myVar = (varname, varValue) Then the dialog return becomes: self.myVar[1] = dialog.myVar.get() You also need to make the dialog smart enough to read the name of the variable (myVar[0]) and set the label accordingly... If you use dynamic variables you will need to pass in the variable name and then use getattr to retrieve the value. Or pass name and value - which sounds a lot like a tuple? The problem with trying to create actual variables is that the rest of yor code must become psychic (or very complex) to figure out what variable to use. Or you write a lott of near identical code to handle every possible variable name! BTW, the Quit function is original but doesn't kill the window when Quit is used. What fixes that? Brute force you can use sys.exit()! But more normally you can use what you have used, so I'm not sure why its not working! For more bonus points, it seems as though the try statement in the dialog should really bring up an "Error" dialog saying something is wrong, when an invalid entry occurs. You can use the standard 'showerror' or 'showwarning' dialogs for that: http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm Finally I note the use of eval() to evaluate the user input. That is bad, bad bad. And looks like there is no need since after eval'ing you then use int(). You should be able to use int() directly on the input and handle any ValueError exceptions etc to catch bad input. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
"Wayne Watson" wrote BTW, the Quit function is original but doesn't kill the window when Quit is used. Does that include running from the command console? Is this another IDLE/Tkinter issue maybe? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
destroy() took care of it, but I wonder what advantage there was to Quit()? destroy destroys the widget, quit exits the main loop. destroying the top level widget usually causes the mainloop; to die too so the end result is the same (provided you have no non-modal dialogs open?). HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
"Wayne Watson" wrote Comments? class IntVar_GUI: I just noticed the name of the class. This kind of implies that you are intending writing GUIs for each data type? That shouldn't be necessary since the inputs will be strings in each case. You only need to call the appropriate conversion function when you pull the data back from the input dialog. The exception might be if you want a different inpuit mechanism - like a drop down list or radio button. In that case the number of GUIs you write is determined by the number of input mechanisms used not the number of data types... Hopefully the mechanism list is shorter than the data type list! Just a thought. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html I browsed through your response, and it looks like this may be doable. I'll look this over more carefully this evening. It seems as though someone should have had a similar problem in the past. The Tkinter interface seems to be a, I hope, temporary logjam. I don't recall XWindow widgets needing the control variable notion. I've already overhauled a lot of the code, and names, initial values are in list/dictionary form. That all works, but I've just started considering how all this can be carried into the two objects mentioned here. Note too that I need to take care of things like self.anumberVar = StringVar(). I noted the eval too. Not my code. When the dust clears, I'll look at it. The program is not for general distribution. As an aside, I've finally latched on to the idea of attributes in Python terms. The idea seems local to Python. Alan Gauld wrote: "Wayne Watson" wrote see my post of yesterday, "Maintaining the Same Variable Type--Tkinter", went over like a lead balloon. :-) Yeah, I had no idea what you meant :-) I've heavily modified the original code to accept a config file, and set up variable to initialize the widgets, trying to bridge some code in the Enter_Data_Dialog and Set_Enter_Data objects control variable code is where the trouble lays Yep, and part of it is the attempt to create variables dynamically. It's so much easier if you use a dictionary or a list of name,value tuples. The code below puts up a window with one menu and two submenus items, Enter Data, and Exit. Select Enter Data and put in an integer number. It all works fine. It works with hard coded variable names. Trying to use dynamic variable names will be much trickier! Basically, what I want to do is eliminate code like dialog.anumberVar.get() and replace it by constructing the appropriate names for the config file. If you used a list of variables you could replace it with self.varList[0][1] = dialog.myVar.get() In this case, the config file might contain: anumber = 123 and you store that as varList.append( (varname, varValue) ) If there is only one variable at a time you could just use the tuple of course: self.myVar = (varname, varValue) Then the dialog return becomes: self.myVar[1] = dialog.myVar.get() You also need to make the dialog smart enough to read the name of the variable (myVar[0]) and set the label accordingly... If you use dynamic variables you will need to pass in the variable name and then use getattr to retrieve the value. Or pass name and value - which sounds a lot like a tuple? The problem with trying to create actual variables is that the rest of yor code must become psychic (or very complex) to figure out what variable to use. Or you write a lott of near identical code to handle every possible variable name! BTW, the Quit function is original but doesn't kill the window when Quit is used. What fixes that? Brute force you can use sys.exit()! But more normally you can use what you have used, so I'm not sure why its not working! For more bonus points, it seems as though the try statement in the dialog should really bring up an "Error" dialog saying something is wrong, when an invalid entry occurs. You can use the standard 'showerror' or 'showwarning' dialogs for that: http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm Finally I note the use of eval() to evaluate the user input. That is bad, bad bad. And looks like there is no need since after eval'ing you then use int(). You should be able to use int() directly on the input and handle any ValueError exceptions etc to catch bad input. HTH, -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html An interesting thought, I'll ponder it. Note though the use of control variables like IntVar, etc. In the 2000 line original version of all the program, integers, dates, and booleans are in use for the simplified widget I produced. Note to the use of self.anumberVar.set. (I think I mixed this up in my first response to you with StringVar.) Alan Gauld wrote: "Wayne Watson" wrote Comments? class IntVar_GUI: I just noticed the name of the class. This kind of implies that you are intending writing GUIs for each data type? That shouldn't be necessary since the inputs will be strings in each case. You only need to call the appropriate conversion function when you pull the data back from the input dialog. The exception might be if you want a different inpuit mechanism - like a drop down list or radio button. In that case the number of GUIs you write is determined by the number of input mechanisms used not the number of data types... Hopefully the mechanism list is shorter than the data type list! Just a thought. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
"Wayne Watson" wrote Note though the use of control variables like IntVar, etc. FWIW. Personally I never use those "convenience" features of Tk. I prefer to explicitly set and get them myself. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html Nope. I just tried it. It works fine from there. Interesting, as far as I know, the author wanted us to run it from IDLE. That may explain some other oddities. I'll check with him. I'm quite sure in his user manual he never talks about the command console. Alan Gauld wrote: "Wayne Watson" wrote BTW, the Quit function is original but doesn't kill the window when Quit is used. Does that include running from the command console? Is this another IDLE/Tkinter issue maybe? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html There's another way? Alan Gauld wrote: "Wayne Watson" wrote Note though the use of control variables like IntVar, etc. FWIW. Personally I never use those "convenience" features of Tk. I prefer to explicitly set and get them myself. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Configuration File, Tkinter, IntVars--Manufacturing Variables
Title: Signature.html Memory malfunction. I've been using the program to add features so much with IDLE my brain went IDLE. One starts it by double clicking on the py file. It is possible some users might have drifted off into IDLE though, but unlikely. Wayne Watson wrote: Nope. I just tried it. It works fine from there. Interesting, as far as I know, the author wanted us to run it from IDLE. That may explain some other oddities. I'll check with him. I'm quite sure in his user manual he never talks about the command console. Alan Gauld wrote: "Wayne Watson" wrote BTW, the Quit function is original but doesn't kill the window when Quit is used. Does that include running from the command console? Is this another IDLE/Tkinter issue maybe? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Signature.html Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page: ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is this [] construction?
Marc Tompkins wrote: > List comprehensions will make your head hurt the first few dozen times you encounter them. After that, they become easier to use than the longer for-loop structure they replace - as André pointed out, they read almost like English. I have to disagree, I immediately fell in love with list comprehension when I first meet them. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is this [] construction?
On Tue, Mar 3, 2009 at 7:01 PM, Lie Ryan wrote: > Marc Tompkins wrote: > > List comprehensions will make your head hurt the first few dozen times > >> you encounter them. After that, they become easier to use than the longer >> for-loop structure they replace - as André pointed out, they read almost >> like English. >> > I have to disagree, I immediately fell in love with list comprehension when > I first meet them. > OK, I over-generalized. They made MY head hurt at first. Now I love them. -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Code documentation
Hello list, I have been coding in python a short while and I have been wondering which approach should I take on documentation (API docs) for a python library I have been working on, there is currently code docstrings, docstrings with some markup (epydoc, etc), or external programs such as Sphinx (reStructuredText markup). In your experience which way is the best or what advantages/disadvantages do you see (experienced) with each approach that you are familiar. Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Convert XML codes to "normal" text?
*So here is my program, I'm pulling some information off of my Snipt feed .. * import feedparser d = feedparser.parse('http://snipt.net/dorseye/feed') x=0 for i in d['entries']: print d['entries'][x].title print d['entries'][x].summary print x+=1 *Output* Explode / Implode List >>> V = list(V) >>> V ['s', 'p', 'a', 'm', 'm', 'y'] >>> V = ''.join(V) >>> V 'spammy' >>> I know, for example, that the > code means >, but what I don't know is how to convert it in all my data to show properly? In all the feedparser examples it just smoothly has the output correct (like in one the data was whatever and it had the special characters just fine.) I didn't notice any special call on their feedparser.parse() and I can't seem to find anything in the feedparser documentation that addresses this. Has anyone run into this before? Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert XML codes to "normal" text?
Eric Dorsey wrote: _So here is my program, I'm pulling some information off of my Snipt feed .._ I know, for example, that the > code means >, but what I don't know is how to convert it in all my data to show properly? In all the feedparser examples it just smoothly has the output correct Why not str.replace()? mystring = mystring.replace('>', '>') (like in one the data was whatever and it had the special characters just fine.) I didn't notice any special call on their feedparser.parse() and I can't seem to find anything in the feedparser documentation that addresses this. Has anyone run into this before? Thanks! It's because > is not the same as >. > is HTML escape sequence for >, which means browser would substitute them to a real > instead of considering it as part of html tags. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert XML codes to "normal" text?
On Wed, Mar 4, 2009 at 11:13 AM, Eric Dorsey wrote: > I know, for example, that the > code means >, but what I don't know is > how to convert it in all my data to show properly? I Feedparser returns the output in html only so except html tags and entities in the output. What you want is to Unescape HTML entities ( http://effbot.org/zone/re-sub.htm#unescape-html ) import feedparser import re, htmlentitydefs def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "": # character reference try: if text[:3] == "": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("?\w+;", fixup, text) d = feedparser.parse('http://snipt.net/dorseye/feed') x=0 for i in d['entries']: print unescape(d['entries'][x].title) print unescape(d['entries'][x].summary) print x+=1 HTH, Senthil ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is this [] construction?
"Andre Engels" wrote What is this: d = [ int(x) for x in s.split(":") ] That's called list comprehension. The notation [f(x) for x in A if p(x)] means: Form a list in the following way: For Wayne's benefit... You will also find a similar construction in parens called a generator expression (like tuoles the parens aren't always necessary but usually help). That produces an iterable that you can loop over without actually creating a list per se. ie you can write: foo = [1,2,3,4] for n in (x for x in foo if x % 2): ... print n ... 1 3 In Python v3 list comprehensions and generator expressions have been "merged" in that putting a GE inside [] has the same effect as a LC. In practice this makes little or no difference to the programmer its just how Python handles it behind the scenes. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor