[Tutor] NLTK
Hello, I have successfully downloaded NLTK and the toy grammars. I want to run a few of the packages that come with NLTK on corpora that I have. How do I do this? What commands would I use? The corpora are text files; should I put them in the Python25 folder (is that the so called same directory)? Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > Now there are a couple of decorators that are in the standard library > that everyone should know about:classmethod() and staticmethod(). > They wrap a method in a new one (which ends up having the same name), > such that the first argument is either eaten (staticmethod), or changed > to a class (classmethod). > > Hope that was sufficient detail. > > DaveA Thank you all for your answer, I read the link posted by Kent end the explanations given by others, and now almost all the pieces of the puzzle are falling to their place. The (last?) thing still escaping my understanding is the difference between classmethod() and staticmethod(). I understand that both of them are to make sure a method will be associated with the class rather than with an instance of it (a bit like variables declared in a class but outside a method), so I assume I should use them like: class myClass(object): @staticmethod / @classmethod def method_of_class(self): pass def method_of_instances(self): pass I am not sure I understood the difference between staticmethod end classmethod, though, even if I can guess it has to do with subclassing, (given classmethod go fish for the class name)... am I on the right track? Any hint (or full-fledged explanation!)? :) [The official documentation is a bit obscure for me as it refers to C# and Java, languages that I do not know.] Also, what is the advantage of using a method at class level rather than using it at object instance (I can imagine you can save some memory by not duplicating X times the same code, maybe... but what kind of designs require/call for use of statc/classmethods?) Thank you in advance for your help, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
On Fri, Aug 28, 2009 at 3:14 AM, Ishan Puri wrote: > Hello, > I have successfully downloaded NLTK and the toy grammars. I want to run > a few of the packages that come with NLTK on corpora that I have. How do I > do this? What commands would I use? The corpora are text files; should I put > them in the Python25 folder (is that the so called same directory)? The section Loading your own Corpus in the book seems to show what you want: http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
Mac Ryan wrote: On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: Now there are a couple of decorators that are in the standard library that everyone should know about:classmethod() and staticmethod(). They wrap a method in a new one (which ends up having the same name), such that the first argument is either eaten (staticmethod), or changed to a class (classmethod). Hope that was sufficient detail. DaveA Thank you all for your answer, I read the link posted by Kent end the explanations given by others, and now almost all the pieces of the puzzle are falling to their place. The (last?) thing still escaping my understanding is the difference between classmethod() and staticmethod(). I understand that both of them are to make sure a method will be associated with the class rather than with an instance of it (a bit like variables declared in a class but outside a method), so I assume I should use them like: class myClass(object): @staticmethod / @classmethod def method_of_class(self): pass def method_of_instances(self): pass I am not sure I understood the difference between staticmethod end classmethod, though, even if I can guess it has to do with subclassing, (given classmethod go fish for the class name)... am I on the right track? Any hint (or full-fledged explanation!)? :) [The official documentation is a bit obscure for me as it refers to C# and Java, languages that I do not know.] Also, what is the advantage of using a method at class level rather than using it at object instance (I can imagine you can save some memory by not duplicating X times the same code, maybe... but what kind of designs require/call for use of statc/classmethods?) Thank you in advance for your help, Mac. I thought someone (me) had already posted examples. The method itself looks different in the three cases: class MyClass(object): def my_method1(self, arg): ... do something with this particular object @classmethod def my_class_method(cls, arg) do something that may requires use of class, but that doesn't need to know the particular object @staticmethod def my_static_method(arg): do something which isn't affected at all by what class it's in self and cls parameters are named that merely by convention. Unlike the "this" of C++, C#, and Java, these names have no specific meaning to the compiler. But convention is a very good thing, especially in this case. So the first difference between static and class is that the method signature must be different. There's an extra parameter on the latter that must be included. The second difference is that a classmethod may call other methods of the same class, and gets the appropriate methods even if the class was subclassed. The hint to play with is that any of these 3 may be called with an object (obj.my_class_method()), and the last two may be called with a classname. DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] What does it mean to create separate applications?
Hi, I'm new to python and frankly new to programming. This is my first question post, so I hope everyone could bear with me. I'm working on a small database application which basically handles a store inventory, it's my internship project for the semester. My boss asked me to break down each form (e.g. product information entry, store inventory list) into separate small applications. I'm having a hard time understanding what she means by this. Does it mean each form is it's separate python file? If that's the case, the things I have already is that way. I guess my question basically is, what does it mean for something to be called an application or a standalone application? I've searched the internet for some answers but I just keep getting more confused. Thanks for any pointers anyone can give me! Best, Krissy ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] packing a list of lists
Back to python after a long long layoff. So i am running into some beginner's confusion... I am trying to plot a list of numbers in gnuplot.py. To do that I am trying to pack the list with an index by iterating over the list so i can get something like: foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] So that i have x, y pairs to plot. When i print in my func i get the right thing, for each item (note scaffolding) yet when i reurn the whole list i just get the last pair repeated over and over. I am not sure why this is. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list # function declarations would go here def test(): """test function - say what this does here and skip a line Keyword arguments: none """ print foo = minus(200) plot_me = pack(foo) #print foo print print plot_me if __name__ == "__main__": test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Fri, 2009-08-28 at 08:55 -0400, Dave Angel wrote: > Mac Ryan wrote: > > On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: > > > > > >> Now there are a couple of decorators that are in the standard library > >> that everyone should know about:classmethod() and staticmethod(). > >> They wrap a method in a new one (which ends up having the same name), > >> such that the first argument is either eaten (staticmethod), or changed > >> to a class (classmethod). > >> > >> Hope that was sufficient detail. > >> > >> DaveA > >> > > > > Thank you all for your answer, I read the link posted by Kent end the > > explanations given by others, and now almost all the pieces of the > > puzzle are falling to their place. > > > > The (last?) thing still escaping my understanding is the difference > > between classmethod() and staticmethod(). I understand that both of them > > are to make sure a method will be associated with the class rather than > > with an instance of it (a bit like variables declared in a class but > > outside a method), so I assume I should use them like: > > > > class myClass(object): > > > > @staticmethod / @classmethod > > def method_of_class(self): > > pass > > > > def method_of_instances(self): > > pass > > > > I am not sure I understood the difference between staticmethod end > > classmethod, though, even if I can guess it has to do with subclassing, > > (given classmethod go fish for the class name)... am I on the right > > track? Any hint (or full-fledged explanation!)? :) > > > > [The official documentation is a bit obscure for me as it refers to C# > > and Java, languages that I do not know.] > > > > Also, what is the advantage of using a method at class level rather than > > using it at object instance (I can imagine you can save some memory by > > not duplicating X times the same code, maybe... but what kind of designs > > require/call for use of statc/classmethods?) > > > > Thank you in advance for your help, > > Mac. > > > > > > > I thought someone (me) had already posted examples. The method itself > looks different in the three cases: > > class MyClass(object): > > def my_method1(self, arg): > ... do something with this particular object > > @classmethod > def my_class_method(cls, arg) > do something that may requires use of class, but > that doesn't need to know the particular object > > @staticmethod >def my_static_method(arg): > do something which isn't affected at all by what > class it's in > > self and cls parameters are named that merely by convention. Unlike the > "this" of C++, C#, and Java, these names have no specific meaning to the > compiler. But convention is a very good thing, especially in this case. > > So the first difference between static and class is that the method > signature must be different. There's an extra parameter on the latter > that must be included. The second difference is that a classmethod may > call other methods of the same class, and gets the appropriate methods > even if the class was subclassed. > > The hint to play with is that any of these 3 may be called with an > object (obj.my_class_method()), and the last two may be called with a > classname. > > DaveA Thank you Dave, very helpful as ever. I made a few tests and experiments to understand better, and I feel I am understanding how it works. Although the mechanic of this is increasingly clear, the logic behind is still a bit obscure: here comes a silly test on which results I have questions about == class A(object): variable = 0 @classmethod def cm(cls): cls.variable += 3 class B(A): pass class C(B): pass a = A() b = B() c = C() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' b.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' c.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.variable = 7 A.variable = 4 print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' B.variable = 'x' print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable == Now, the output of this test is as follows (I manually added the numbers on the right for reference in the remaining of the post): 0 0 # 1 0 0 0 0 --- 3 3 # 2 3 3 3 3 --- 3 3 # 3 6 6 6 6 --- 3 3 # 4 6 6 9 9 --- 4 7 # 5 6 6 9 9 --- 4 7 # 6 x x 9 9 #1 is plain obvious. #2 came as a bit of surprise: "Ah-ah!... so the class variable is the same for all the hierarchy of classes! I would have guessed each class had its own variable..." #3 and #4 are bigge
Re: [Tutor] packing a list of lists
On Fri, Aug 28, 2009 at 8:05 AM, kevin parks wrote: > Back to python after a long long layoff. So i am running into some > beginner's confusion... > > I am trying to plot a list of numbers in gnuplot.py. To do that I am trying > to pack the list with an index by iterating over the list so i can get > something like: > > foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] > > [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] > > So that i have x, y pairs to plot. When i print in my func i get the right > thing, for each item (note scaffolding) yet when i reurn the whole list i > just get the last pair repeated over and over. > > I am not sure why this is. > > > def pack(in_seq): >out_list=[] >x = 1 >ll=[1, 1] >for each in in_seq: >ll[0] = x >ll[1] = each >out_list.append(ll) >#print ll >x = x + 1 >print out_list > > > # function declarations would go here > def test(): >"""test function - say what this does here and skip a line > >Keyword arguments: >none >""" > >print >foo = minus(200) >plot_me = pack(foo) >#print foo >print >print plot_me > > > if __name__ == "__main__": >test() > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Although I didn't test your code, I think what you are trying to accomplish can be done using enumerate cleaner def pack(foo): out = [] for x,y in enumerate(foo, 1): out.append((x,y)) return out ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
On Fri, Aug 28, 2009 at 9:18 AM, vince spicer wrote: > > > On Fri, Aug 28, 2009 at 8:05 AM, kevin parks wrote: > >> Back to python after a long long layoff. So i am running into some >> beginner's confusion... >> >> I am trying to plot a list of numbers in gnuplot.py. To do that I am >> trying to pack the list with an index by iterating over the list so i can >> get something like: >> >> foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] >> >> [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] >> >> So that i have x, y pairs to plot. When i print in my func i get the right >> thing, for each item (note scaffolding) yet when i reurn the whole list i >> just get the last pair repeated over and over. >> >> I am not sure why this is. >> >> >> def pack(in_seq): >>out_list=[] >>x = 1 >>ll=[1, 1] >>for each in in_seq: >>ll[0] = x >>ll[1] = each >>out_list.append(ll) >>#print ll >>x = x + 1 >>print out_list >> >> >> # function declarations would go here >> def test(): >>"""test function - say what this does here and skip a line >> >>Keyword arguments: >>none >>""" >> >>print >>foo = minus(200) >>plot_me = pack(foo) >>#print foo >>print >>print plot_me >> >> >> if __name__ == "__main__": >>test() >> >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > Although I didn't test your code, I think what you are trying to accomplish > can be done using enumerate cleaner > > > def pack(foo): > out = [] > for x,y in enumerate(foo, 1): > out.append((x,y)) > return out > > > > Or even cleaner with list comprehension def pack(foo): return [x for x in enumerate(foo, 1)] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
Kevin Parks wrote: > def pack(in_seq): > out_list=[] > x = 1 > ll=[1, 1] > for each in in_seq: > ll[0] = x > ll[1] = each > out_list.append(ll) > #print ll > x = x + 1 > print out_list Variable out_list consists of list ll repeated however many times. Each time you change ll you're changing it everywhere it appears in out_list. That is, what's being appended to out_list isn't a copy of ll, it's a pointer to ll. You need something like:- out_list.append([ll[0],ll[1]]) And you need to add a return at the end of the function, otherwise it returns None: return out_list -- Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] flyweight pattern using Mixin vs. Inheritance
Hi everyone, Based on some earlier list advice, I went back to the drawing board and started testing various approaches to adding the "flyweight" pattern to my classes. To recap, I have a bunch of campaign finance-related classes and subclasses (Committee, HouseCommittee, PresidentialCommittee, Candidate, CampaignReport, etc.), and I'm trying to add in the ability for a class to check for a unique instance of itself before creating a new instance. So if I have a committee named "Pac1", I want to check if that committee has previously been created. If it does exist, I want to return the "Pac1" instance; otherwise, I want to create the "Pac1" instance. The closest description I could find to this pattern was the "flyweight" (described here: http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#behavioural-patterns), though it appears that this pattern relates as much (or more?) to efficient memory usage than to the notion of only creating a new instance if an identical one does not already exist. (If there's a name for the latter piece of this pattern, please let me know so I can avoid typing that phrase over and over again!) I pasted my test code for two approaches to solving this problem, one using a Mixin class and another using Inheritance. http://pastebin.com/m3252c407 I'm not certain I'll need this functionality on all occasions, and not all of my classes/subclasses require this behavior. Given those requirements, is the Mixin approach the way to go? Either way, have I implemented these correctly? Also, for purposes of the test, please note that I commented out the weakref usages (which kind of defeats the purpose of the flyweight pattern, right?). It was easier to wrap my brain around this when the instance ids remained the same. I found that when using weakref, the ids changed (even for what should have been the same instance). Is that due to the nature of how garbage collection works with weakref? Or perhaps I'm not implementing this pattern correctly? Hence my asking you all! As always, any and all advice is appreciated. Serdar ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
Mac Ryan wrote: On Fri, 2009-08-28 at 08:55 -0400, Dave Angel wrote: Mac Ryan wrote: On Wed, 2009-08-26 at 21:32 -0400, Dave Angel wrote: Now there are a couple of decorators that are in the standard library that everyone should know about:classmethod() and staticmethod(). They wrap a method in a new one (which ends up having the same name), such that the first argument is either eaten (staticmethod), or changed to a class (classmethod). Hope that was sufficient detail. DaveA Thank you all for your answer, I read the link posted by Kent end the explanations given by others, and now almost all the pieces of the puzzle are falling to their place. The (last?) thing still escaping my understanding is the difference between classmethod() and staticmethod(). I understand that both of them are to make sure a method will be associated with the class rather than with an instance of it (a bit like variables declared in a class but outside a method), so I assume I should use them like: class myClass(object): @staticmethod / @classmethod def method_of_class(self): pass def method_of_instances(self): pass I am not sure I understood the difference between staticmethod end classmethod, though, even if I can guess it has to do with subclassing, (given classmethod go fish for the class name)... am I on the right track? Any hint (or full-fledged explanation!)? :) [The official documentation is a bit obscure for me as it refers to C# and Java, languages that I do not know.] Also, what is the advantage of using a method at class level rather than using it at object instance (I can imagine you can save some memory by not duplicating X times the same code, maybe... but what kind of designs require/call for use of statc/classmethods?) Thank you in advance for your help, Mac. I thought someone (me) had already posted examples. The method itself looks different in the three cases: class MyClass(object): def my_method1(self, arg): ... do something with this particular object @classmethod def my_class_method(cls, arg) do something that may requires use of class, but that doesn't need to know the particular object @staticmethod def my_static_method(arg): do something which isn't affected at all by what class it's in self and cls parameters are named that merely by convention. Unlike the "this" of C++, C#, and Java, these names have no specific meaning to the compiler. But convention is a very good thing, especially in this case. So the first difference between static and class is that the method signature must be different. There's an extra parameter on the latter that must be included. The second difference is that a classmethod may call other methods of the same class, and gets the appropriate methods even if the class was subclassed. The hint to play with is that any of these 3 may be called with an object (obj.my_class_method()), and the last two may be called with a classname. DaveA Thank you Dave, very helpful as ever. I made a few tests and experiments to understand better, and I feel I am understanding how it works. Although the mechanic of this is increasingly clear, the logic behind is still a bit obscure: here comes a silly test on which results I have questions about == class A(object): variable = 0 @classmethod def cm(cls): cls.variable += 3 class B(A): pass class C(B): pass a = A() b = B() c = C() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' b.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' c.cm() print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' a.variable = 7 A.variable = 4 print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable print '---' B.variable = 'x' print A.variable, a.variable print B.variable, b.variable print C.variable, c.variable == Now, the output of this test is as follows (I manually added the numbers on the right for reference in the remaining of the post): 0 0 # 1 0 0 0 0 --- 3 3 # 2 3 3 3 3 --- 3 3 # 3 6 6 6 6 --- 3 3 # 4 6 6 9 9 --- 4 7 # 5 6 6 9 9 --- 4 7 # 6 x x 9 9 #1 is plain obvious. #2 came as a bit of surprise: "Ah-ah!... so the class variable is the same for all the hierarchy of classes! I would have guessed each class had its own variable..." #3 and #4 are bigger surprises: "Uh? let me understand better, so... it must be like branches... as soon as I say that B.variable is different than its ancestors, all the descendants of B get updated... Yet, it's strang
Re: [Tutor] Callbacks in Python
Jramak wrote: Thanks everyone for your excellent insights. I think I understand the callback concept better. So, it is like passing a function as an argument to another function. I am interested in learning more about how callbacks can be applied in GUIs, using wxPython as an example. Would appreciate any insight. Thanks much Jramak On 8/27/09, Alan Gauld wrote: "Jramak" wrote I'm confused by callbacks. I would really appreciate any introduction or help in understanding the concept of callbacks. Callbacks are used in all sorts of different ways in programming so it might help to undertand what exactly confuses you. Is it the whole concept of a callback? Is it the idea of a function as an object? Is it the use of callbacks? In a GUI? In a networking framework like Twisted? Do you want to use someone elses callback mechanism or do you want to create your own? The basic name comnes from the concept of calling someone, asking them to do someting then call you back when they are done. So you leave your number with them. The number you leave is what they "call back". In programming you call a function and at some critical point that function calls you back on the function that you passed in. def someFunction(value, callback) result = pow(value,2) callback(result) def myFunction() v = 42 someFunction(v, myFunction_continue) def myFunction_contiinue(result) print result myFunction() This was very useful before threading environments became common as a way of simulating multi threading. Then when GUIs came along it bacame a common way of associating functions with widgets. And in networking we can associate network events with functions in a similar way. In fact any kind of event driven program is likely to use callbacks as a way of distributing control depending on event type. The typical implementation will see the event framework storing the callbacks in some kind of dictionary keyed by event type. HTH, -- Alan Gauld 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 If you have any sample code for wxPython, look for the Bind method. Generally used within widget code, it passes a reference to a method that should be called when some specific event happens to that widget. In the following line, if the widget gets resized (by the user dragging the edges of the window), my method OnSize() will be called. self.Bind(wx.EVT_SIZE, self.OnSize) DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
Thanks for the replies. Though the list comprehension does not work: TypeError: enumerate() takes exactly 1 argument (2 given) On Aug 29, 2009, at 12:20 AM, vince spicer wrote: #print foohough I didn't test your code, I think what you are trying to accomplish can be done using enumerate cleaner def pack(foo): out = [] for x,y in enumerate(foo, 1): out.append((x,y)) return out Or even cleaner with list comprehension def pack(foo): return [x for x in enumerate(foo, 1)] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
On Fri, Aug 28, 2009 at 10:49 AM, kevin parks wrote: > > Thanks for the replies. Though the list comprehension does not work: > > TypeError: enumerate() takes exactly 1 argument (2 given) > > > On Aug 29, 2009, at 12:20 AM, vince spicer wrote: > > >> >> #print foohough I didn't test your code, I think what you are trying >> to accomplish can be done using enumerate cleaner >> >> >> def pack(foo): >>out = [] >>for x,y in enumerate(foo, 1): >>out.append((x,y)) >>return out >> >> >> >> >> Or even cleaner with list comprehension >> >> def pack(foo): >>return [x for x in enumerate(foo, 1)] >> >> >> > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > What version of python are using, python 2.6+ have a "start" parameter http://docs.python.org/library/functions.html#enumerate ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
"Mac Ryan" wrote I am not sure I understood the difference between staticmethod end classmethod, though, even if I can guess it has to do with subclassing, I think it is mainly historical. staticmethod came first (I think) and classmethod was an improvement a couple of versions later. I think classmethod is the preferred choice nowadays. Also, what is the advantage of using a method at class level rather than using it at object instance There are two common cases: 1) You want to do something at the class level rather than instance level - such as find all instances, or keep a count of all instances. Or you may have a method or variable that affects all instances simultaneously - perhaps activates or disables all network connections say. 2) You want somethig that can be done without creating an instance, or at least does not depend on whether any instances exist yet. This is very common in Java which doesn't support standalone functions but is not needed so much in Python because a module function is usually a better option. You can also use it to provide meta-class programming features and other tricks, but frankly thats usually being too clever for your own good! :-) HTH, -- Alan Gauld 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] What does it mean to create separate applications?
Kristina Ambert wrote: Hi, I'm new to python and frankly new to programming. This is my first question post, so I hope everyone could bear with me. I'm working on a small database application which basically handles a store inventory, it's my internship project for the semester. My boss asked me to break down each form (e.g. product information entry, store inventory list) into separate small applications. I'm having a hard time understanding what she means by this. Does it mean each form is it's separate python file? If that's the case, the things I have already is that way. I guess my question basically is, what does it mean for something to be called an application or a standalone application? I've searched the internet for some answers but I just keep getting more confused. Thanks for any pointers anyone can give me! Best, Krissy An application is something the end-user can run by itself. Typically, a python application is a script dedicated to one purpose, that may import other python modules that are more general purpose, and those may be shared between applications. At its simplest, such a script parses the command line arguments (sys.argv) does some initialization, and invokes some features in the shared code of those imports. A standalone application is one that's ready to install and use on an arbitrary machine, without having much in the way of external dependencies. But that's very dependent on the customer base you're aiming at. For example, python.exe (and all its libraries ) is a dependency, but a particular company may already assume every machine has a particular version of Python installed and ready to go. Now, different levels of management may have different notions of what an application is. For example, to some people, maybe an application is something that can be run from a Windows Desktop shortcut, with all other interactions being prompted by the program itself. So they want to see separate shortcuts for "product entry", "store inventory" etc. Now if I were doing these, they might all invoke the same Python script, but pass parameters choosing what subset of features are needed. As long as "installation" includes initializing these shortcuts, the manager is happy. DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What does it mean to create separate applications?
"Kristina Ambert" wrote inventory, it's my internship project for the semester. My boss asked me to break down each form (e.g. product information entry, store inventory list) into separate small applications. I'm having a hard time understanding what she means by this. Does it mean each form is it's separate python file? Pretty much. I guess my question basically is, what does it mean for something to be called an application or a standalone application? I've searched the internet for some answers but I just keep getting more confused. An "application" is a pseudonym for most users for a "program". But to a programmer a "program" can also mean the complete source code for an application. So to distinguish between program (source code) and program(executable) the term application is often used. So I suspect your boss wants a separate exercutable python script for each main form. By using modules you should be able to reuse a lot of your database code between the different applications. You will find more on this topic in the "What is Programming" topic in my tutorial. HTH, -- Alan Gauld 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] packing a list of lists
I think this is b/c I am running 2.5. I also have 2.6 but i am using 2.5 for gnupoly and an older audio lib i have. I ran the listcom below on 2.6 and it worked, so i just have to figure out how that can be written for 2.5. I guess 2.6 has an update to enumerate. -k On Aug 29, 2009, at 2:21 AM, afit...@gmail.com wrote: Enumerate() is returning a tuple, I haven't tested this code but try: [[x[0],x[1]] for x in enumerate(blah,1)] --Original Message-- Sender: tutor-bounces+afith13+python=gmail@python.org To: tutor@python.org Subject: Re: [Tutor] packing a list of lists Sent: Aug 28, 2009 9:49 AM Thanks for the replies. Though the list comprehension does not work: TypeError: enumerate() takes exactly 1 argument (2 given) On Aug 29, 2009, at 12:20 AM, vince spicer wrote: #print foohough I didn't test your code, I think what you are trying to accomplish can be done using enumerate cleaner def pack(foo): out = [] for x,y in enumerate(foo, 1): out.append((x,y)) return out Or even cleaner with list comprehension def pack(foo): return [x for x in enumerate(foo, 1)] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flyweight pattern using Mixin vs. Inheritance
"Serdar Tumgoren" wrote Given those requirements, is the Mixin approach the way to go? Either way, have I implemented these correctly? I haven't looked at your code but you could use a mixin here however I find using mixins for insantiation can bend your brain. I tend to use them for instance behavioural type things . Instead I would actually use a dictionary class attribute (see the thread on class attributes/methods) The way I'd do it would be to store a dictionary of object instances (using some kind of unique name/id as key). In the constructor of each class (ie __new__() not __init__() check to see if the ID exists in the dictionary and return the object if it does. Otherwise continue as usual. Something like this(untested pseudo code): class A instances = {} def __new__(self, ID, *args, **kwargs): if ID in instances: return ID def __init__(self, *args, **kwargs): if ID in self.instances: return else: # init as usual. def __del__(self): del( self.instances[self.ID] ) The __del__ can probably be implemented in the top level class and inherited. HTH, -- Alan Gauld 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] packing a list of lists
kevin parks wrote: Back to python after a long long layoff. So i am running into some beginner's confusion... I am trying to plot a list of numbers in gnuplot.py. To do that I am trying to pack the list with an index by iterating over the list so i can get something like: foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] So that i have x, y pairs to plot. When i print in my func i get the right thing, for each item (note scaffolding) yet when i reurn the whole list i just get the last pair repeated over and over. I am not sure why this is. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list # function declarations would go here def test(): """test function - say what this does here and skip a line Keyword arguments: none """ print foo = minus(200) plot_me = pack(foo) #print foo print print plot_me if __name__ == "__main__": test() Your specific problem is that you're not building new lists, you're just reusing the same one each time through the loop. The most brute-force fix for the problem is to use the slice operator to make a copy of the list before appending it to the outer list. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll[:])#make a copy of ll, and append that copy #print ll x = x + 1 print out_list pack(in_seq) #But that's not efficient. Better would be to construct a new list each time (and I'm going to avoid using variables that look like numbers): def pack(in_seq): out_list=[] x = 1 for each in in_seq: item = [x, each] out_list.append(item) #print ll x = x + 1 print out_list pack(in_seq) #or even: def pack(in_seq): out_list=[] x = 1 for each in in_seq: out_list.append( [x, each] ) #print ll x = x + 1 print out_list pack(in_seq) #Note that there's a useful function enumerate which could help here: def pack(in_seq): out_list=[] for x, each in enumerate(in_seq): item = [x+1, each] #(too bad you want your integers to start at 1; Python likes zero-based out_list.append(item) #print ll print out_list pack(in_seq) #and that could be simplified further def pack(in_seq): out_list=[] for item in enumerate(in_seq): item = list(item)#turn the tuple into a list item[0] += 1 #because you're 1-based instead of zero-based out_list.append(item) #print ll print out_list pack(in_seq) #and one more step, using zip() to combine two lists def pack(in_seq): out_list = zip(xrange(1, 1+len(in_seq)), in_seq) print out_list pack(in_seq) HTH DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] thread causes idle to crash
hello, I've been working on threads and queues and I think I have it working well. The problem seems to be that when I run a thread via the IDLE it crashes. if I simply double click the file it appears to run ok. I'm not sure if I'm doing something incorrectly or not. it seems pretty straight forward. my sample code is listed below. I'm using Python 2.6.2, and I'm running on Microsoft Vista. Any thoughts would be much appreciated. thanks! Jeff import threading import Queue import time, random WORKERS = 2 class Worker(threading.Thread): def __init__(self, queue): self.__queue = queue threading.Thread.__init__(self) def run(self): while 1: item = self.__queue.get() if item is None: break # reached end of queue # pretend we're doing something that takes 10-100 ms time.sleep(random.randint(10, 100) / 100.0) print "task", item, "finished" # # try it queue = Queue.Queue(0) for i in range(WORKERS): print 'starting' Worker(queue).start() # start a worker for i in range(10): print 'putting' queue.put(i) for i in range(WORKERS): print 'putting None' queue.put(None) # add end-of-queue markers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
Interestingly changing: out_list.append(ll) to out_list.append(list(ll)) seems to work. The part of my brain that understood why that is must have sleeping. -k On Aug 28, 2009, at 11:05 PM, i wrote: Back to python after a long long layoff. So i am running into some beginner's confusion... I am trying to plot a list of numbers in gnuplot.py. To do that I am trying to pack the list with an index by iterating over the list so i can get something like: foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] So that i have x, y pairs to plot. When i print in my func i get the right thing, for each item (note scaffolding) yet when i reurn the whole list i just get the last pair repeated over and over. I am not sure why this is. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list # function declarations would go here def test(): """test function - say what this does here and skip a line Keyword arguments: none """ print foo = minus(200) plot_me = pack(foo) #print foo print print plot_me if __name__ == "__main__": test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
On Aug 29, 2009, at 12:23 AM, Michael M Mason wrote: i wrote: def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list Variable out_list consists of list ll repeated however many times. Each time you change ll you're changing it everywhere it appears in out_list. That is, what's being appended to out_list isn't a copy of ll, it's a pointer to ll. You need something like:- out_list.append([ll[0],ll[1]]) Right... ugh.. Totally forgot about that. Python 101. I don't know why my brain resists that idea. Every time i let python alone a while and come back to it i get bit by this. And you need to add a return at the end of the function, otherwise it returns None: return out_list That, of course, i know... I was messing around debugging of course. Thanks for the response. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
On Fri, Aug 28, 2009 at 11:20 AM, vince spicer wrote: > Or even cleaner with list comprehension > > def pack(foo): > return [x for x in enumerate(foo, 1)] Or just list(enumerate(foo, 1)) For Python 2.5 use [ [i+1, x] for i, x in enumerate(foo) ] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
On Fri, Aug 28, 2009 at 10:28 AM, kevin parks wrote: > Interestingly changing: > out_list.append(ll) > > to > > out_list.append(list(ll)) > > > seems to work. The part of my brain that understood why that is must have > sleeping. Because it makes a new list instead of appending many references to the same list. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flyweight pattern using Mixin vs. Inheritance
I was able to resolve the error by explicitly naming the class in the dictionary lookup inside __new__: if candid in CandidateAuto.instances: return candid I'm curious why this is necessary though. From our earlier dicussions (and from other reading), I thought that by declaring a static class attribute, that it would automatically become available to an instances of that class. My impression was that that a method searches for the variables/attributes in it's local scope, and failing to find it there, would bubble up to the class level and find the static variable there. Is that not correct? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Making sense of "'python' is not recognized as an internal or external command...
Hello, list. Sorry, for this basic question. But why in Windows (XP) command prompt I get this message if, for example I type "python myscript.py"? But it works if I simply type myscript.py? Maybe by getting an answer for this question I could know how to make commands "grep, diff" work from any folder, and not have to type the full path for them or start in their folder...-- I have GnuWin32 utilities installed in my c:\Program Files. Thanks, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running two applications at once
hi, I'm new to python, and I'm starting with Python 3.1 directly. I have been learning python for about 2 weeks now. And I have few questions. Is it possible if I run two applications at once? For example, if I make a clock/timer application with alarm etc, then I want exercise with my python, creating other codes, and running it. Is it possible? If I can make the application as stand-alone application (executeable EXE file - I'm using Windows XP), then there should be no problem. But as far that I know, py2exe doesnt support python version 3 yet. Does anyone know anyway to convert python to exe for python 3.1? Thank you. Dirk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Store Class in Tuple Before Defining it ...
Hi - I would like to have a tuple that holds information, as such: VIDEO_TYPES = ( (SyncYoutube, re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), ) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Store Class in Tuple Before Defining it ...
Sorry for the double post! Went off by mistake before I was done ... Anyhow, I would like to have a tuple defined at the beginning of my code that includes classes *before* they are defined ... as such (this is on-the-fly-hack-code just for demonstrating my question): VIDEO_TYPES = ( (SyncYoutube, re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), (SyncVimeo, re.compile(#more regex here#),), (SyncBlip, re.compile(#more regex here#),), ) class Video(object): url = "http://youtube.com/"; #variables ... def sync(self): for videotype in VIDEO_TYPES: #check the url against the regex, # if it matches then initiate the appropriate class and pass it the current "self" object sync = videotype[0](self).sync() class SyncYoutube(object): def __init__(self,video): self.video = video def sync(self): #do some custom Youtube syncing here class SyncBlip(object): #etc This way, I can get any video object and simply run Video.sync() and it will figure out which "sync" to run. However, I am finding (of course) that I can't reference a class that hasn't been defined! I know this is a rush-job question, but I am hoping someone seems my quandary and maybe has a way around it. I am learning python as we speak! Thanks! And sorry for the double post. Damon On Fri, Aug 28, 2009 at 5:10 PM, Damon Timm wrote: > Hi - > > I would like to have a tuple that holds information, as such: > > VIDEO_TYPES = ( > (SyncYoutube, > re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), > > ) > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running two applications at once
hi, I'm new to python, and I'm starting with Python 3.1 directly. I have been learning python for about 2 weeks now. And I have few questions. Is it possible if I run two applications at once? For example, if I make a clock/timer application with alarm etc, then I want exercise with my python, creating other codes, and running it. Is it possible? If I can make the application as stand-alone application (executeable EXE file - I'm using Windows XP), then there should be no problem. But as far that I know, py2exe doesnt support python version 3 yet. Does anyone know anyway to convert python to exe for python 3.1? Thank you. Dirk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sending an email alert
Hello, I am trying to code an email alert and am running into the following error: Connecting to server Traceback (most recent call last): File "C:\Users\Marc1\Documents\Python\email test\email.py", line 1, in import smtplib File "C:\Python26\lib\smtplib.py", line 46, in import email.utils File "C:\Users\Marc1\Documents\Python\email test\email.py", line 12, in s = smtplib.SMTP('smtp.marcd.org') AttributeError: 'module' object has no attribute 'SMTP' The code I am trying to use is: import smtplib import time >From ="m...@mydomain.org" To = ["m...@mydomain.org"] Date = time.ctime(time.time()) Subject = "Email Python Test" Text = "It Works!!" mMessage = ('From %s\nTo: %s\nDate: %s\nSubject: %s\n%s\n' % (From, To, Date, Subject, Text)) print 'Connecting to server' s = smtplib.SMTP('smtp.mydomain.org') rCode = s.sendmail(From, To, mMessage) s.quit() if rCode: print 'Error sending message' else: print 'message sent' Of course, I am substituting m...@mydoamin.org with my email address and 'smtp.mydomain.org' with my domain email server. The error seems to say that the method or function SMTP does not exist within smtplib, but if I run the lines import smtplib s = smtplib.SMTP('smtp.mydomain.org') in IDLE, it connects and then times out, as I would expect. I tried this on Windows and Linux with the same result. Thanks, Marc What am I missing here? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running two applications at once
"Dirk Wangsadirdja" wrote Is it possible if I run two applications at once? Yes, you just run two instances of the python interpreter. They will happuily run independantly of one another or communicate with each other as you wish. Its exactly the same as with Java or Visual Basic or any other interpreter. If I can make the application as stand-alone application (executeable EXE file - I'm using Windows XP), then there should be no problem. But as far that I know, py2exe doesnt support python version 3 yet. You don;t nered py2exe just run the two scripts, windows XP will start two copies of python based on the .py extension. 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
Re: [Tutor] Making sense of "'python' is not recognized as an internalor external command...
"Eduardo Vieira" wrote Hello, list. Sorry, for this basic question. But why in Windows (XP) command prompt I get this message if, for example I type "python myscript.py"? But it works if I simply type myscript.py? In the latter case Windows usees a registry setting to pick up what program to use. In the first case it looks for python in its PATH. (Notice this is different to PYTHONPATH!) Unfortunately the Windows installer no longer automatically adds Python to your PATH you have to do this yourself. To check that this works you can do it from a command window by typing SET PATH %PATH%;C:\Program Files\Python26 Or whatever the actual path to your python is. After typing that you should find you can type Python from anywhere on your PC and it will work. If that solves the problem you now need to add it to the envirtonment variables so that it is set every time. This is done via MyComputer->Properties->Advanced->Environment Variables Select Path and click Edit Be very careful not to accidentally delete the existing path! add your Python folder to the end of the existing path separating it with a semi-colon. That should work! HTH, -- Alan Gauld 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
[Tutor] Using my own corpus with NLTK
Hi, Thanks for your response. I tried this and got to the 3rd line. However, when I type in the fourth: >>> wordlists.fileids() a blank comes as a result. When I try the len() function it only counts the letters in title of the text document IM50re.txt. How do I get it to open and analyze the text, as they have done with the Gutenberg texts at the beginning of the chapter? Or more generally, how does one import a .txt document to analyze in Python? I have downloaded the packages to analyze my data with in Python. Thank you.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flyweight pattern using Mixin vs. Inheritance
class A: > instances = {} > def __new__(self,ID): > if ID in self.instances: > return self.instances[ID] > else: > self.instances[ID] = self > return self > def __init__(self, ID): > if ID not in self.instances: > print("unregistered instance!") > def __del__(self): > del(self.instances[self.ID]) > Aha! I should have done some tweaking. Many thanks as always! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
On Fri, Aug 28, 2009 at 6:09 PM, Ishan Puri wrote: > Hi, > Thanks for your response. I tried this and got to the 3rd line. However, > when I type in the fourth: > wordlists.fileids() > > a blank comes as a result. When I try the len() function it only counts the > letters in title of the > text document IM50re.txt. How do I get it to open and analyze the text, as > they have done > with the Gutenberg texts at the beginning of the chapter? Did you give the correct path to your files? How did you use len()? It helps if you show what you tried and what result you got. Please Reply All to reply to the list. Kent > Thank you. > > > > > From: Kent Johnson > To: Ishan Puri > Cc: Python Tutor > Sent: Friday, August 28, 2009 4:49:40 AM > Subject: Re: [Tutor] NLTK > > On Fri, Aug 28, 2009 at 3:14 AM, Ishan Puri > wrote: >> Hello, >> I have successfully downloaded NLTK and the toy grammars. I want to >> run >> a few of the packages that come with NLTK on corpora that I have. How do I >> do this? What commands would I use? The corpora are text files; should I >> put >> them in the Python25 folder (is that the so called same directory)? > > The section Loading your own Corpus in the book seems to show what you want: > http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
Hi, >>> from nltk.corpus import PlaintextCorpusReader >>> corpus_root='C:\Users\Ishan\Documents' >>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>> wordlists.fileids() ['IM50re.txt'] This is the result I get. I was wondering how I can use the packages on IM50re.txt? I followed successfully the steps detailed under Using Your Own Corpus. What do I do next, say, if I wanted to use the lemmatizer on this .txt document? Thank you. From: Kent Johnson To: Ishan Puri Cc: *tutor python Sent: Friday, August 28, 2009 4:24:19 PM Subject: Re: [Tutor] NLTK On Fri, Aug 28, 2009 at 6:09 PM, Ishan Puri wrote: > Hi, > Thanks for your response. I tried this and got to the 3rd line. However, > when I type in the fourth: > wordlists.fileids() > > a blank comes as a result. When I try the len() function it only counts the > letters in title of the > text document IM50re.txt. How do I get it to open and analyze the text, as > they have done > with the Gutenberg texts at the beginning of the chapter? Did you give the correct path to your files? How did you use len()? It helps if you show what you tried and what result you got. Please Reply All to reply to the list. Kent > Thank you. > > > > > From: Kent Johnson > To: Ishan Puri > Cc: Python Tutor > Sent: Friday, August 28, 2009 4:49:40 AM > Subject: Re: [Tutor] NLTK > > On Fri, Aug 28, 2009 at 3:14 AM, Ishan Puri > wrote: >> Hello, >> I have successfully downloaded NLTK and the toy grammars. I want to >> run >> a few of the packages that come with NLTK on corpora that I have. How do I >> do this? What commands would I use? The corpora are text files; should I >> put >> them in the Python25 folder (is that the so called same directory)? > > The section Loading your own Corpus in the book seems to show what you want: > http://nltk.googlecode.com/svn/trunk/doc/book/ch02.html > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Store Class in Tuple Before Defining it ...
On Fri, Aug 28, 2009 at 5:21 PM, Damon Timm wrote: > Sorry for the double post! Went off by mistake before I was done ... > > Anyhow, I would like to have a tuple defined at the beginning of my > code that includes classes *before* they are defined ... as such (this > is on-the-fly-hack-code just for demonstrating my question): > > VIDEO_TYPES = ( > (SyncYoutube, > re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*'),), > (SyncVimeo, re.compile(#more regex here#),), > (SyncBlip, re.compile(#more regex here#),), > ) > > class Video(object): > url = "http://youtube.com/"; > #variables ... > > def sync(self): > for videotype in VIDEO_TYPES: > #check the url against the regex, > # if it matches then initiate the appropriate class and > pass it the current "self" object > sync = videotype[0](self).sync() > > class SyncYoutube(object): > def __init__(self,video): > self.video = video > > def sync(self): > #do some custom Youtube syncing here > > class SyncBlip(object): > #etc > > > This way, I can get any video object and simply run Video.sync() and > it will figure out which "sync" to run. However, I am finding (of > course) that I can't reference a class that hasn't been defined! Just move the definition of VIDEO_TYPES after the def'n of the classes it uses. Video.sync() will compile just fine, it doesn't need VIDEO_TYPES to be defined until it is executed. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Store Class in Tuple Before Defining it ...
"Damon Timm" wrote Anyhow, I would like to have a tuple defined at the beginning of my code that includes classes *before* they are defined ... as such (this is on-the-fly-hack-code just for demonstrating my question): See another recent thread - you can't do it. What you could do is put your classes in another module and then import that module. Or you could put the tuple initialisation into a function. But its probably easiest to just move the definition to the bottom of the file... HTH, -- Alan Gauld 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] Sending an email alert
On Fri, Aug 28, 2009 at 3:00 PM, Marc wrote: > Hello, > > > > I am trying to code an email alert and am running into the following error: > > Connecting to server > > Traceback (most recent call last): > > File "C:\Users\Marc1\Documents\Python\email test\email.py", line 1, in > > > import smtplib > > File "C:\Python26\lib\smtplib.py", line 46, in > > import email.utils > > File "C:\Users\Marc1\Documents\Python\email test\email.py", line 12, in > > > s = smtplib.SMTP('smtp.marcd.org') > > AttributeError: 'module' object has no attribute 'SMTP' Your file 'email.py' is hiding the std lib 'email' module and this is creating a circular import and basically a mess :-) Try calling your program something else. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
On Fri, Aug 28, 2009 at 7:29 PM, Ishan Puri wrote: > Hi, from nltk.corpus import PlaintextCorpusReader corpus_root='C:\Users\Ishan\Documents' wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') wordlists.fileids() > ['IM50re.txt'] > > This is the result I get. That seems to be working then. You should be able to get a list of words with wordlists.words('IM50re.txt') > I was wondering how I can use the packages on > IM50re.txt? I followed successfully the steps detailed under Using Your Own > Corpus. What do I do next, say, if I wanted to use the lemmatizer on this > .txt document? I have no idea. Is IM50re.txt a plain text corpus? What is a package? What is a lemmatizer? I don't know anything about NLTK, I'm just good at reading manuals. You have to give me more help than that. What have you tried? Can you find an example that is similar to what you want to do? Don't assume I know what you are talking about :-) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
Hi, Thanks for the confirmation. IM50re.txt is a plain text corpus. Let us say that we want to count the words in this corpus. In the NLTK book, there is an example. >>> import nltk >>> nltk.corpus.gutenberg.fileids() ['austen-emma.txt', 'austen-persuasion.txt', 'austen-sense.txt', 'bible-kjv.txt', 'blake-poems.txt', 'bryant-stories.txt', 'burgess-busterbrown.txt', 'carroll-alice.txt', 'chesterton-ball.txt', 'chesterton-brown.txt', 'chesterton-thursday.txt', 'edgeworth-parents.txt', 'melville-moby_dick.txt', 'milton-paradise.txt', 'shakespeare-caesar.txt', 'shakespeare-hamlet.txt', 'shakespeare-macbeth.txt', 'whitman-leaves.txt'] These are the texts that come with NLTK. >>> emma = nltk.corpus.gutenberg.words('austen-emma.txt') >>> len(emma) 192427 So this is the number of words in a particular 'austen-emma.txt'. How would I do this with my IM50re.txt? It seems the code "nltk.corpus.gutenberg.words" is specific to some Gutenberg corpus installed with NLTK. Like this many examples are given for different analyses that can be done with NLTK. However they all seem to be specific to one of the texts above or another one already installed with NLTK. I am not sure how to apply these examples to my own corpus. Thank you. You are my own source of help right now; I have been trying to figure this out all day now. From: Kent Johnson To: Ishan Puri Cc: *tutor python Sent: Friday, August 28, 2009 7:03:15 PM Subject: Re: [Tutor] NLTK On Fri, Aug 28, 2009 at 7:29 PM, Ishan Puri wrote: > Hi, from nltk.corpus import PlaintextCorpusReader corpus_root='C:\Users\Ishan\Documents' wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') wordlists.fileids() > ['IM50re.txt'] > > This is the result I get. That seems to be working then. You should be able to get a list of words with wordlists.words('IM50re.txt') > I was wondering how I can use the packages on > IM50re.txt? I followed successfully the steps detailed under Using Your Own > Corpus. What do I do next, say, if I wanted to use the lemmatizer on this > .txt document? I have no idea. Is IM50re.txt a plain text corpus? What is a package? What is a lemmatizer? I don't know anything about NLTK, I'm just good at reading manuals. You have to give me more help than that. What have you tried? Can you find an example that is similar to what you want to do? Don't assume I know what you are talking about :-) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sending an email alert
> On Fri, Aug 28, 2009 at 3:00 PM, Marc wrote: > > Hello, > > > > > > > > I am trying to code an email alert and am running into the following > error: > > > > s = smtplib.SMTP('smtp.marcd.org') > > > > AttributeError: 'module' object has no attribute 'SMTP' > > Your file 'email.py' is hiding the std lib 'email' module and this is > creating a circular import and basically a mess :-) > > Try calling your program something else. > > Kent That did it - Thanks!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] general import VS importing inside a function
What is the best aproach when it comes to import??, is allways better to make all the import calls in the global scope, making the overall runtime of the program better because the program is not going to import something everytime a function is called, or is better to make specific import's inside a function making the function completely portable?? here's a example: case 1: # importing in the global scope import foo variable = "somethin here" def bar(value1, value2): return value1, value2 = foo.foo Case 2: # importing inside a function variable = "somethin here" def bar(value1, value2): import foo return value1, value2 = foo.foo and another thing, making specific import, makes the program less, how you said this "RAM eater" (sorry my native language is spanish and i dont now how to translate "cosume menos recursos" google says "cosumes less resources", but anyway i hope you get it) I say this because, for example when i'm in the interactive shell and import big things like Scipy, and NumPy, python takes 3 to 5 seconds to respond, and if am only going to use like 4 or 5 function inside NumPy i think is better to say just "from Numpy import foo, bar, qux etc" but i would actually like to read this from someone that knows about programming and not just me making asumptions... salu2! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor