Re: [Tutor] Tkinter event handler
On 13/01/12 03:44, Chase Franklin wrote: I'd like to include the class name so that it becomes: 001_Jan_12_2012_CLASSNAME.org So I have a simple Tk window that is populated by a list of class names. What is a "Simple Tk window"? There is no such widget. So what is the window using to list the names? Is it a label? a text widget? or a List entry woidget(which would seem the most logical) 1. Class One 2. Class Two 3. Class Three Idealy, at this prompt I'd like to simply press the corresponding number and be on to emacs with the Class Name added to the file name When you say press the "number" do you mean you want the user to point at the digit part of the line? Why not just have them click on the line itself? That's what a list entry does by default. You can then select as much or as little of the seleced text to put in your filename. as above. I know how to hard code this for each keypress, but is there a way to create the events dynamically so that when the list changes the keys follow suit? I hope I've been clear enough, thanks! I don;t undertsamd this at all. Tk events are all created dynamically but they have nothing to do ewith the content of the list. I think you need to show us some code. At the moment its not at all clear(to me) what you are trying to do. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read in text file containing non-English characters
>You don't show even a snippet of code. If you are asking >for help here, it is good form to show us your code. Since >you don't state how you are reading the data and how you are >printing the data, we can't help much. Here are some tips: > > * Consider learning how to use the csv module, particularly in >your case, csv.reader (as Ramit Prasad has already suggested). > > * Consider checking the bytestream to see if the bytes produced >on output are the same as on input (also, read the text that >Mark Tompkins indicated and learn to distinguish Unicode from >UTF-8). > > * Report back to the list the version of Python you are using. >[Different versions of Python have subtly different handling of >non ASCII character set data, but this should probably not be an >issue for the more obvious issue you are showing above.] > >We can have no idea what your ultimate goal is with the data, but >can help you much more if you show us the code. > >Here's a sample of what I would/could do (Python 2.6.5): > >import csv >reader = csv.reader(open('input-data.txt'),delimiter=',') >for row in reader: >print 'The capital of %s is %s' % (row[0], row[1],). > >The above is trivial, but if you would like some more substantive >assistance, you should describe your problem in a bit more detail. I apologize for not including any code, but that's because I didn't have any. I had no idea where to even begin. I have a 450 page book on beginner Python programming and nothing like the above is in there. Incidentally, when I try the above code in Python 3.2 I get an "invalid syntax" message. My ultimate goal is to be able to do what I've done for years in SAS, where I consider myself an expert: read in some raw data, perform some mathematical operations on the data, then output it. Later this spring I will be teaching an audience that does not have access to SAS (community college students) and Python was suggested as an alternative. IMPORTANT NOTICE: This e-mail and any attachments may contain confidential or sensitive information which is, or may be, legally privileged or otherwise protected by law from further disclosure. It is intended only for the addressee. If you received this in error or from someone who was not authorized to send it to you, please do not distribute, copy or use it or any attachments. Please notify the sender immediately by reply e-mail and delete this from your system. Thank you for your cooperation. <>___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PYTHONPATH (Mac OS X)
* Stayvoid [2011-12-30 16:11]: > >You don't have any option. > >You either type in the full path or you get the user to tell you > >in some way - either with a prompt or via an input argument. > > OK, now I get it. > > How can I tell this to the end-user? > Should I write a README file or what? > > I've tried to run lengthcounter_lutz from the file's folder and this worked > out. > cd /Users/Username/Python_modules/ > python /Users/Username/Python_modules/lengthcounter_lutz.py > ('Lines:', 12, 'Chars:', 285) > > > But I can't understand what's wrong with the second one: > def countLines(name): > file = open(name.__file__) > return len(file.readlines()) > > def countChars(name): > return len(open(name.__file__).read()) > > def test(name): > return "Lines:", countLines(name), "Chars:", countChars(name) > > if __name__ == '__main__': > import lengthcounter > print test(lengthcounter) > > >>> import lengthcounter > >>> lengthcounter.test(lengthcounter) > ('Lines:', 5, 'Chars:', 885) > Looking at page 1119 in the learning Python book, I might venture a guess as to where the difference lies. You are calling test as: test(lengthcounter), but that is not the name of a file (the name of a file should be in quotes). lengthcounter in this case is a variable, not a filename. The behavior in this case is probably undetermined. I suggest doing a manual check on the file named lengthcounter.pyc, and I'll bet you will find something closer to 5 lines and 885 characters. pyc files are the bytecode version of your file that gets generated automatically and is the code that is actually executed. Somehow, calling the method test inside the interpreter is different from running it on the commandline and you are picking up the pyc file. In either case, this format is iffy at best: if __name__ == '__main__': import lengthcounter print test(lengthcounter) should really be: if __name__ == '__main__': import lengthcounter print lengthcounter.test(lengthcounter) to avoid ambiguous behavior. -- David Rock da...@graniteweb.com pgpc2h7KXfB8z.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Are there other ways of solving this exercise?
Wow!!! Thanks so much for your reply. It was so nicely written and I understood everything you said. Thanks again, have a nice weekend. Regards, Amt. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read in text file containing non-English characters
Greetings Francis, : >You don't show even a snippet of code. If you are asking : >for help here, it is good form to show us your code. Since : >you don't state how you are reading the data and how you are : >printing the data, we can't help much. Here are some tips: : > : > * Consider learning how to use the csv module, particularly in : >your case, csv.reader (as Ramit Prasad has already suggested). : > : > * Consider checking the bytestream to see if the bytes produced : >on output are the same as on input (also, read the text that : >Mark Tompkins indicated and learn to distinguish Unicode from : >UTF-8). : > : > * Report back to the list the version of Python you are using. : >[Different versions of Python have subtly different handling of : >non ASCII character set data, but this should probably not be an : >issue for the more obvious issue you are showing above.] : > : >We can have no idea what your ultimate goal is with the data, but : >can help you much more if you show us the code. : > : >Here's a sample of what I would/could do (Python 2.6.5): : > : >import csv : >reader = csv.reader(open('input-data.txt'),delimiter=',') : >for row in reader: : >print 'The capital of %s is %s' % (row[0], row[1],). : > : >The above is trivial, but if you would like some more substantive : >assistance, you should describe your problem in a bit more detail. : : : I apologize for not including any code, but that's because I : didn't have any. I had no idea where to even begin. I have a 450 : page book on beginner Python programming and nothing like the : above is in there. Incidentally, when I try the above code in : Python 3.2 I get an "invalid syntax" message. One of the famous differences between Python 2.x and Python 3.x [0] is 'print'. Try this: import csv reader = csv.reader(open('input-data.txt'),delimiter=',') for row in reader: print('The capital of %s is %s' % (row[0], row[1],)) : My ultimate goal is to be able to do what I've done for years in : SAS, where I consider myself an expert: read in some raw data, : perform some mathematical operations on the data, then output it. : Later this spring I will be teaching an audience that does not : have access to SAS (community college students) and Python was : suggested as an alternative. OK, so this list is a good place to be for such initial explorations. There are a number of libraries that can help with the mathematical operations and you will probably get many good suggestions. Welcome to the list, -Martin [0] http://wiki.python.org/moin/Python2orPython3 -- Martin A. Brown http://linux-ip.net/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter event handler
I apologize, I didn't realize how tired I was. I've got it working, sort of, after finding the event.char attribute. I needed it to work via keyboard since I don't use a mouse often and I'm running this with awesome-wm's launcher so it can't get input from the terminal (as far as I know) and I didn't know another way to have it prompt me for input except with Tk. Here's what I've got: def key(event): class_list = read_object('.create_note_classes') # pickle file list of class names class_list.sort() class_name = class_list[int(event.char) - 1] id = new_id() # this gets the appropriate number for filename ex: 001 today = get_date() # gets date and formats it filename = '%03d_%s_%s.org' % (id, today, class_name) ## ex: 001_Jan_13_2012_Economics.org window.destroy() subprocess.call(['emacs', filename]) class_list = read_object('.create_note_classes') class_list.sort() window = Tk() for i, v in enumerate(class_list): v = Label(text='%d %s' % (i + 1, v)).pack() window.bind_all('', key) window.mainloop() I'm going to change this to use the listbox widget though since you mentioned it. It's ugly I know, this is the first thing I've tried writing with python (2.7 btw). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Read in text file containing non-English characters
Hi Francis, On 13 January 2012 14:52, Francis P. Boscoe wrote: >> I apologize for not including any code, but that's because I didn't have >> any. I had no idea where to even begin. I have a 450 page book on beginner >> Python programming and nothing like the above is in >there. Incidentally, >> when I try the above code in Python 3.2 I get an "invalid syntax" message. As mentioned by Martin, the reason you get a syntax error is because the print statement doesn't exist anymore in Python 3.x -- It's been replaced with a print() function to make it more consistent with the rest of the language. That said, please be aware that there's many changes between Python 2.x and 3.x, even though they look and act more similar than not. Nevertheless you should be aware of which major version you're using and make adjustments accordingly. As of right now, unless you have particular reason to do so, I'd say stick with Python 2.7 and only switch to Python 3.2 or better once you have a handle on the basics on unless you have a specific reason to go with 3.x. However, one of the big differences as mention before between Python 2.x and 3.x is Unicode handling so this might be one reason for you to actually have a more serious look at Python 3.x despite what I've just suggested... Also, for reference, the following presentation which discusses differences between Python 2 and Python 3 from an I/O p.o.v. but also comments quite a bit on the Unicode changes (Unicode has a direct impact on text I/O) and related subtleties that might bight one if you're not careful: http://www.slideshare.net/dabeaz/mastering-python-3-io-version-2 HTH, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] read in text file containing non-English characters
On 13/01/12 08:20, Francis P. Boscoe wrote: Given a simple text file of departments, capitals, longitude and latitude separated by commas Ahuachapán,Ahuachapán,-89.8450,13.9190 Cabañas,Sensuntepeque,-88.6300,13.8800 Cuscatlán,Cojutepeque,-88.9333,13.7167 I would like to know to how to read in the file and then access arbitary rows in the file, so that I can print a line such as: The capital of Cabañas is Sensuntepeque while preserving the non-English characters What version of Python are you using? This is likely to be easier in Python 3.1 or 3.2; if you can upgrade to either of those, that will make your life easier in the long run. First off, you need to know what encoding the source file is. You call it a "simple text file", but there is no such thing once you include non-ASCII values! The truth is, there never was such a thing, but so long as people only included ASCII characters in files, we could ignore the complexity. If you don't understand what I mean by "encoding", I strongly recommend you read Joel On Software: http://www.joelonsoftware.com/articles/Unicode.html If you don't know what the encoding is, you have to guess, or give up. Possibly ask the supplier of the file. There are software libraries which will read a text file and try to guess the encoding for you. Or when in doubt, just try UTF-8. I have created a text file containing the three lines above, starting with Ahuachapán. Because I have created it, I know that the encoding I used was UTF-8. (If you are creating your own data files, *always* use UTF-8 unless you have a specific reason why you shouldn't.) But I'm going to pretend that I don't know this, and show you what happens when I get the encoding wrong. This is using Python 2.6. py> import codecs py> for line in codecs.open('test.txt', encoding='latin1'): ... print line.strip() # strip() removes the trailing newline ... Ahuachapán,Ahuachapán,-89.8450,13.9190 Cabañas,Sensuntepeque,-88.6300,13.8800 Cuscatlán,Cojutepeque,-88.9333,13.7167 So I got the encoding wrong. The incorrect characters like ñ are often known by the Japanese term "moji-bake", and that's a good sign of encoding problems. Here's another wrong guess: py> for line in codecs.open('test.txt', encoding='ascii'): ... print line.strip() ... Traceback (most recent call last): [ ... traceback deleted for brevity ... ] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 8: ordinal not in range(128) So when you get the encoding wrong, two things may happen: you get an error, telling you you got it wrong, or you get junk output, which if you are really unlucky might look like legitimate output. This is what happens when I use the correct encoding: py> for line in codecs.open('test.txt', encoding='utf8'): ... print line.strip() ... Ahuachapán,Ahuachapán,-89.8450,13.9190 Cabañas,Sensuntepeque,-88.6300,13.8800 Cuscatlán,Cojutepeque,-88.9333,13.7167 It just works perfectly. Now, this is how to actually do some useful work with the data. Assuming you are using at least version 2.6 (possibly even 2.5, but definitely not 2.4) this should work nicely: py> from collections import namedtuple py> Record = namedtuple('Record', 'capital region x y') py> data = [] py> for line in codecs.open('test.txt', encoding='utf8'): ... line = line.strip() ... data.append(Record(*line.split(','))) ... py> for record in data: ... print "The capital of", record.region, "is", record.capital ... The capital of Ahuachapán is Ahuachapán The capital of Sensuntepeque is Cabañas The capital of Cojutepeque is Cuscatlán Hope this helps and gets you started. Regards, -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trying to access a random value in a list
On 13/01/12 10:56, Nick W wrote: first problem: easy fix just remember that len() returns the actual number of items in the list but that list is indexed starting at 0 so just replace your line of pick = len(names) with: pick = len(names) - 1 Another good trick for choosing a random value from a list is to avoid picking a number first and just ask for a random choice: >>> import random >>> L = ['spam', 'ham', 'cheese', 'eggs'] >>> random.choice(L) 'cheese' and for problem #2: just use string formating... like for example instead of: print (names[win_number], " is the winner!") try something along the lines of: print("{} is a winner".format(names[win_number])) Apart from being longer and harder, is there an advantage to the second form? :) A third alternative is: print("%s is a winner" % names[win_number]) In any case, none of these solve the actual problem. The original poster is talking about printing the list of names: print (names, "have been entered.") which prints an actual LIST, so you get (e.g.): ['fred', 'barney'] instead of: fred barney The easy way to fix that is to use: print (" ".join(names), "have been entered.") -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor