[Tutor] How to open a file with images
Hi everybody! In Java we have the appletviewer and frames, through which we can access image files. In python, if I want to open an image file in IDLE, how can I do that, and what should my command look like? Many thanks Vikas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Codehelp: confused by the output in IDLE
Hi again! The following is a piece of code that I have written: def funcA(x): # function describiing the oddness or eveness of an x number if x%2 == 0: print x, "is even" else: print x, "is odd" def funcB(y): # function describiing the oddness or eveness of an y number if y%2 ==0: print y, "is even" else: print y, "is odd" # no more functions after this line x=input("Please type a number: ")print x y=input("Please type another number: ")print y if x>y: print x,("is greater than"),yelse: print y,("is greater than"),x if y and x >=0: print ("Both are positive numbers!") print funcA(x)print funcB(y) And this is the output in IDLE after execution: Please type a number: 55Please type another number: 101010 is greater than 5Both are positive numbers!5 is oddNone10 is evenNone I don't understand why I am getting 2 instances of "None" in the output, when it has not been programmed by me. What is going on? Pls. advice Thanks again, V ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Accessing next and previous items during iteration
Is it possible to access the next and previous items during an iteration? I want to use it to iterate through html files in a folder and add links in to the next and previous pages. For example for page in folder: #add link to previous page #add link to next page I'm currently using: prev = 0 current = 0 next = 0 for page in folder: prev = current current = next next = page if current: if prev: #add link to previous page #add link to next page if current: if prev: #add link to previous page #add link to next page But this seems a really awkward way to do it. I've considered iterating and dumping them all into a list and then iterating through the list, but that also seems awkward (having to iterate twice). Is there a nice way to do it? Thanks Ed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I fix this StopIteration error?
Nathan Pinno wrote: >>store = open(filename,'r') >for line in store: > conv = line.strip() > rate = float(store.next().strip()) > exch[conv] = rate > > When I ran the program, I got this: > > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 45, in -toplevel- > load_rates(rates) > File "D:\Python24\exchange.py", line 19, in load_rates > rate = float(store.next().strip()) > StopIteration > > How do I fix this? StopIteration is an iterator's way of saying it has reached the end. When you iterate using a for loop, the exception is caught internally and used to terminate the loop. When you call next() explicitly, you should be prepared to catch the exception yourself. In this case though, the exception means you have a conv without a rate, so it is a symptom of bad data or an error reading the data. Have you looked at the file to make sure it is correct? If it is, you might try a slightly different loop. I'm not sure if it really works to mix a for loop iteration with calls to next() on the iterator. Try something like this: store = open(filename,'r') try: while True: conv = store.next().strip() rate = float(store.next().strip()) exch[conv] = rate except StopIteration: pass Or use the pickle module to save and load your exch dictionary, it is perfect for this and as simple as import pickle # save store = open(filename, 'wb') pickle.dump(exch, store) store.close() # load store = open(filename, 'b') exch = pickle.load(store) store.close() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple XML parsing
Tim Wilson wrote: > Hi everyone, > > I've got a little project that requires me to parse a simple XML > file. The file comes from the browser history of Apple's Safari and > includes the URL that was visited, the title of the Web page, the > date and time it was last visited, and the total number of times it > was visited. Here's a snippet: > > > www.apple.com/DTDs/PropertyList-1.0.dtd"> > > > > Let's say that instead of one , the xml file had 100 of them. I > want to generate a simple table of URLs and the dates they were last > visited. I can handle everything except parsing the XML file and > extracting the information. These look promising: http://online.effbot.org/2005_03_01_archive.htm#elementplist http://www.shearersoftware.com/software/developers/plist/ though the empty for the URL might be a problem. The effbot version could be changed to "dict": lambda x: dict((x[i].text or 'url', x[i+1].text) for i in range(0, len(x), 2)), to change empty keys to 'url'; as long as there is only one per (and it is actually the url) that will work. If these don't work you can use ElementTree to do the parse and walk the results tree yourself to pull out the data. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to open a file with images
vikas mohan wrote: > Hi everybody! > > In Java we have the appletviewer and frames, through which we can access > image files. In python, if I want to open an image file in IDLE, how can > I do that, and what should my command look like? Here is a simple program to open an image file and display it using PIL and Tkinter. It is based on an example program that comes with PIL. http://effbot.org/imagingbook/imagetk.htm import Image, ImageTk from Tkinter import Tk, Label im = Image.open('wire.png') class UI(Label): def __init__(self, master, im): if im.mode == "1": # bitmap image self.image = ImageTk.BitmapImage(im, foreground="white") Label.__init__(self, master, image=self.image, bg="black", bd=0) else: # photo image self.image = ImageTk.PhotoImage(im) Label.__init__(self, master, image=self.image, bd=0) root = Tk() UI(root, im).pack() root.mainloop() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Codehelp: confused by the output in IDLE
> def funcA(x): # function describiing the oddness or eveness of an x number > if x%2 == 0: >print x, "is even" > else: >print x, "is odd" >def funcB(y): # function describiing the oddness or eveness of an y number > if y%2 ==0: >print y, "is even" > else: >print y, "is odd" These two functions are identical. What you call the parameter is irrelevant to the outside world its only a local name inside the function! Neither function returns a value so Python will silently return the special value 'None' Also its usually a bad idea to do the printing of results inside the function, its better to return the result and let the caller display the result. Thus a better solution here is probably: def isOdd(x): return x % 2 Now you can do things like: x = int(raw_input('Type a number: ')) y = int(raw_input('Type a number: ')) if isOdd(x): print x, ' is odd' else: print x, ' is even' if isOdd(y): print y, ' is odd' else: print y, ' is even' > *if x>y: > print x,("is greater than"),y > else: > print y,("is greater than"),x* > > *if y and x >=0: > print ("Both are positive numbers!")* This doesn't work because Python will evaluate it like: if y if x >=0: print ... you need to use if y >=0 and x >= 0 print ... > *print funcA(x) > print funcB(y)* Because your functions don't retuirn any value Python returns None. So that is the value that you print. Thats why its probably better to return the result of the test and lat your calling program display the result as described above. > 10 is greater than 5 > Both are positive numbers! This is because of the incorrect if test > 5 is odd This is printed inside the function > None And this is what was returned by the function > 10 is even > None* and the same here HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Codehelp: confused by the output in IDLE
vikas mohan wrote: > Hi again! > > The following is a piece of code that I have written: > > def funcA(x): # function describiing the oddness or eveness of an x number > if x%2 == 0: > print x, "is even" > else: > print x, "is odd" > > def funcB(y): # function describiing the oddness or eveness of an y number > if y%2 ==0: > print y, "is even" > else: > print y, "is odd" > > # no more functions after this line > > *x=input("Please type a number: ") > print x* > > *y=input("Please type another number: ") > print y* > > *if x>y: > print x,("is greater than"),y > else: > print y,("is greater than"),x* > > *if y and x >=0: > print ("Both are positive numbers!")* > > print funcA(x) > print funcB(y) > > And this is the output in IDLE after execution: > > *Please type a number: 5 > 5 > Please type another number: 10 > 10 > 10 is greater than 5 > Both are positive numbers! > 5 is odd > None > 10 is even > None* > > > I don't understand why I am getting 2 instances of "None" in the output, > when it has not been programmed by me. What is going on? > > Pls. advice > > Thanks again, > V You print inside your function (print x, "is odd") and you print the result of your function (print funcA(x)). As your function doesn't explicitly return a value, you get None, see: http://www.python.org/doc/2.4.2/tut/node6.html#SECTION00660 So either just call the function or return the string from your function. HTH, Wolfram ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing next and previous items during iteration
Ed Singleton wrote: > Is it possible to access the next and previous items during an iteration? There is nothing built in to support this directly. > I'm currently using: > > prev = 0 > current = 0 > next = 0 > for page in folder: > prev = current > current = next > next = page > if current: > if prev: > #add link to previous page > #add link to next page > if current: > if prev: > #add link to previous page > #add link to next page I think there is a bug here - when the loop exits, prev, current and next will all be valid with next containing the last page. You have already added the links to current, it is next that needs a link to the previous page. > > But this seems a really awkward way to do it. > > I've considered iterating and dumping them all into a list and then > iterating through the list, but that also seems awkward (having to > iterate twice). You don't say what kind of object folder is. If it is a directory listing e.g. from os.listdir() then it is already a list. In any case you should be able to make a list without an explicit iteration using pages = list(folder) > > Is there a nice way to do it? How about this: pages = list(folder) # make sure we have a list for i, page in enumerate(pages): if i > 0: previous = pages[i-1] # add link to previous if i+1 < len(pages): next = pages[i+1] # add link to next Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python - SQL paradigm (Will I need a hammer to make it fit?)
On 12/16/05, bob <[EMAIL PROTECTED]> wrote: > At 02:14 AM 12/14/2005, Liam Clarke wrote: > >Hi all, > > > >Just contemplating. > > > >If in Python I were organising a data index along the lines of - > > > >j = { > > > >"k_word1" : ["rec1","rec2","rec3","rec4"], > >... > >"k_wordn" :["recX","rec4"] > > > >} > > > >and I was going to find records that matched by seeing what record > >occurred in the most lists (via set intersections or similar; going to > >have a play see what works faster) selected by searching keywords... > > > >how easily does that translate to a SQL table and query format? > > Data modeling looks for relationships between objects. Relationships > can be 1-1 1-many or many-many. Your case is a many-many > (each keyword may appear in one or more records, and each record may > contain one or more keywords.) The customary way to represent this in > a relational database 3 tables. One with one row per keyword, one > with one row per record and one "junction" or "association" table > with one row for each keyword-record pair. > > KEYWORD TABLE > kid keyword > 1cat > 2dog > 3mouse > 4bird > 5banana > > RECORD TABLE > rid record > 1rexX > 2rec4 > 3recAB > 4rec99 > 5recFoo > > KEYWORD-RECORD TABLE > kid rid > 1 1 > 1 3 > 1 4 > 2 2 > 3 5 > 4 1 > 5 3 > > For processing things like this nothing IMHO beats a relational > database and SQL. With many databases accessible from Python I > strongly suggest this approach. SQLite is especially attractive. > [snip] > > Ah... so then on the last table I would use something along the lines of select rid where kid = 1... thanks for that, it was the modelling it part I was finding tricky. And yeah, I have pysqlite up and ready to go. I wrote a basic tutorial for it when it was 1.x :) (On account of how people like me need tutorials sometimes, although I have managed to use BeautifulSoup and py2exe today for the first time, so I've definitely progressed beyond when I first looked at them.) Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing next and previous items during iteration
| Is it possible to access the next and previous items during an | iteration? | | I want to use it to iterate through html files in a folder and add | links in to the next and previous pages. | I just did this :-) What I did was 1) use the glob module to get a list of the files in the directory (*.htm) 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. for i, fil in enumerate(flist): if i<>1: prev = flist[i-1] #do previous link if i<> len(flist): next = flist[i+1] #do next link /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing next and previous items during iteration
| Is it possible to access the next and previous items during an | iteration? | | I want to use it to iterate through html files in a folder and add | links in to the next and previous pages. | I just did this :-) What I did was 1) use the glob module to get a list of the files in the directory (*.htm) 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. for i, fil in enumerate(flist): if i<>1: prev = flist[i-1] #do previous link if i<> len(flist): next = flist[i+1] #do next link /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing next and previous items during iteration
| Is it possible to access the next and previous items during an | iteration? | | I want to use it to iterate through html files in a folder and add | links in to the next and previous pages. | I just did this :-) What I did was 1) use the glob module to get a list of the files in the directory (*.htm) 2) sort this using a special sort function (in my case the files were named as #_# where # was a number and I wanted to sort according to the first number and subsort according to the second) 3) then I just stepped through the list using enumerate and used the index to find the next and previous names in the list, e.g. for i, fil in enumerate(flist): if i<>1: prev = flist[i-1] #do previous link if i<> len(flist): next = flist[i+1] #do next link /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing next and previous items during iteration
Chris or Leslie Smith wrote: > I just did this :-) What I did was > > 1) use the glob module to get a list of the files in the directory (*.htm) > 2) sort this using a special sort function (in my case the files were named > as #_# where # was a number and I wanted to sort according to the first > number and subsort according to the second) > 3) then I just stepped through the list using enumerate and used the index to > find the next and previous names in the list, e.g. > You have a couple of errors in your conditionals > > for i, fil in enumerate(flist): > if i<>1: > prev = flist[i-1] This should be 'if i >= 1'. If i==0 your condition will be true and you will set prev = flist[-1] which is the *last* item in flist. > #do previous link > if i<> len(flist): > next = flist[i+1] should be 'if i+1 < len(flist)' to avoid an IndexError on the last element. Kent > #do next link > > > /c > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] synchronized enumeration
Has anyone else run into the desire to synchronize the indices that are being used during an enumeration with the true indices of the list that is being enumerated when you use a slice of the list? e.g. more than a couple of times, I want to use the enumeration function, but I don't want to start at the beginning of a list. I do something like: ### for i, x in enumerate(aList[3:]): pass #do something with the index and or x ### Of course, if I do something with x in this case, there is no problem, but (often enough) I forget that the index 0 that is returned by enumerate is actually corresponding to index 3 (b/c that's where I started the slice). What I would love to see--and is there a chance of this being considered--is something like the following behavior for enumerate: ### def enumerate(l, start=None, stop=None, step=None, alwaysPos = False): if step==None:step=1 if start==None: if step<0: start=-1 else: start=0 for i, dat in enumerate(l[start:stop:step]): j = i*step+start if alwaysPos and j<0: j+=len(l) yield j, dat for i, x in enumerate(range(5),3): print i, x ### which gives output: 3 3 4 4 rather than enumerate(range(5)[3:])'s output of 0 3 1 4 Any thoughts? /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] synchronized enumeration
Chris or Leslie Smith wrote: > Has anyone else run into the desire to synchronize the indices that are being > used during an enumeration with the true indices of the list that is being > enumerated when you use a slice of the list? > > e.g. more than a couple of times, I want to use the enumeration function, but > I don't want to start at the beginning of a list. I do something like: > > ### > for i, x in enumerate(aList[3:]): > pass #do something with the index and or x > > ### > > Of course, if I do something with x in this case, there is no problem, but > (often enough) I forget that the index 0 that is returned by enumerate is > actually corresponding to index 3 (b/c that's where I started the slice). > > What I would love to see--and is there a chance of this being considered--is > something like the following behavior for enumerate: > > ### > def enumerate(l, start=None, stop=None, step=None, alwaysPos = False): > if step==None:step=1 > if start==None: > if step<0: > start=-1 > else: > start=0 > for i, dat in enumerate(l[start:stop:step]): > j = i*step+start > if alwaysPos and j<0: j+=len(l) > yield j, dat > > for i, x in enumerate(range(5),3): > print i, x > ### > > which gives output: > > 3 3 > 4 4 > > rather than enumerate(range(5)[3:])'s output of > > 0 3 > 1 4 > > Any thoughts? Take a look at this thread on c.l.py for some discussion and possibilities. The part you are interested in starts around message 14. http://groups.google.com/group/comp.lang.python/browse_frm/thread/ab1658dca4023e2b?hl=en&; If you seriously want this to be considered for inclusion in Python you will need to broaden the discussion beyond this list. PEP 1 outlines the official process for getting something added to Python; it doesn't show the unofficial process which usually seems to involve a discussion on c.l.py or python-dev. http://www.python.org/peps/pep-0001.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How do I fix this IndexError?
Kent and all, Here is the latest code: import pickle rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} def save_rates(exch): store = open("exch.txt",'w') pickle.dump(conv,rate) store.close() def load_rates(exch): store = open('exch.txt','r') exch = pickle.load(store) store.close() And here is the latest error: The Currency Exchange Program By Nathan Pinno Traceback (most recent call last): File "D:\Python24\exchange.py", line 36, in -toplevel- load_rates(rates) File "D:\Python24\exchange.py", line 13, in load_rates exch = pickle.load(store) File "D:\Python24\lib\pickle.py", line 1390, in load return Unpickler(file).load() File "D:\Python24\lib\pickle.py", line 872, in load dispatch[key](self) File "D:\Python24\lib\pickle.py", line 1207, in load_appends mark = self.marker() File "D:\Python24\lib\pickle.py", line 888, in marker while stack[k] is not mark: k = k-1 IndexError: list index out of range How do I fix this error? Thanks for all the help so far, Nathan Pinno, MSN Messenger: [EMAIL PROTECTED] Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 StopIteration is an iterator's way of saying it has reached the end. When you iterate using a for loop, the exception is caught internally and used to terminate the loop. When you call next() explicitly, you should be prepared to catch the exception yourself. In this case though, the exception means you have a conv without a rate, so it is a symptom of bad data or an error reading the data. Have you looked at the file to make sure it is correct? If it is, you might try a slightly different loop. I'm not sure if it really works to mix a for loop iteration with calls to next() on the iterator. Try something like this: store = open(filename,'r') try: while True: conv = store.next().strip() rate = float(store.next().strip()) exch[conv] = rate except StopIteration: pass Or use the pickle module to save and load your exch dictionary, it is perfect for this and as simple as import pickle # save store = open(filename, 'wb') pickle.dump(exch, store) store.close() # load store = open(filename, 'b') exch = pickle.load(store) store.close() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I fix this IndexError?
> import pickle > rates = {'can_us' : 0.80276, > 'us_can' : 1.245702, > 'can_euro' : 1.488707, > 'euro_can' : 0.671724} > > def save_rates(exch): > store = open("exch.txt",'w') > pickle.dump(conv,rate) > store.close() Hi Nathan, You may want to double check the use of pickle.dump(). I'm not sure I'm understanding what values are being passed here: what is 'conv' and what is 'rate' here? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I fix this IndexError?
Danny, 'conv' is for the name of the conversion [i.e 'can_us'] and rate is for the conversion rate [i.e. 0.80276] Thanks, Nathan Pinno, MSN Messenger: [EMAIL PROTECTED] Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -Original Message- From: Danny Yoo [mailto:[EMAIL PROTECTED] Sent: December 16, 2005 3:49 PM To: Nathan Pinno Cc: tutor@python.org Subject: Re: [Tutor] How do I fix this IndexError? > import pickle > rates = {'can_us' : 0.80276, > 'us_can' : 1.245702, > 'can_euro' : 1.488707, > 'euro_can' : 0.671724} > > def save_rates(exch): > store = open("exch.txt",'w') > pickle.dump(conv,rate) > store.close() Hi Nathan, You may want to double check the use of pickle.dump(). I'm not sure I'm understanding what values are being passed here: what is 'conv' and what is 'rate' here? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [tutor] Python magazines?
Is there a monthly Python hardcopy magazine? Otherwise what general programming mags carry the most python articles? Thx! RC _ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ElementTree in Python 2.5!
This is great news. And the thread on comp.lang.python is awesome. The eff-bot and the martelli-bot and everyone's just talking about how great it would be to have it in the core, and, then, it just ... happens. Wow! gsf On Wed, Dec 14, 2005 at 03:20:38PM -0500, Kent Johnson wrote: > By some miracle of the gods smiling and the planets aligning, a > comp.lang.python thread that started with the question "ElementTree - > Why not part of the core?" has actually resulted in ElementTree > *becoming* part of the core for Python 2.5! Pretty cool! So the core > Python distribution will finally have a Pythonic XML processor. > > Kent > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/e095cc79d1efb99/a4523a6e9b7061af?rnum=1#a4523a6e9b7061af > > > ___ > 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] How do I fix this IndexError?
Nathan Pinno wrote: > Danny, > > 'conv' is for the name of the conversion [i.e 'can_us'] and rate is for the > conversion rate [i.e. 0.80276] Look at the pickle docs and my previous example. These are not the correct arguments to dump(). Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [tutor] Python magazines?
CPIM Ronin wrote: > Is there a monthly Python hardcopy magazine? Otherwise what general > programming mags carry the most python articles? PyZine seems to be resuming publication: http://www.pyzine.com/index_html I don't know any mags with good Python coverage. I read comp.lang.python and many python-related blogs such as Planet Python http://planet.python.org/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor