Re: [Tutor] PDF Scrapping
Oh, I forgot to mention that I am using Python 3.4. Thanks again for your help pointing me in the right direction. ~Chris On Tue, Nov 24, 2015 at 1:36 PM, Python Beginner < pythonbeginner...@gmail.com> wrote: > Hi, > > I am looking for the best way to scrape the following PDF's: > > (1) > http://minerals.usgs.gov/minerals/pubs/commodity/gold/mcs-2015-gold.pdf > (table on page 1) > > (2) > http://minerals.usgs.gov/minerals/pubs/commodity/gold/myb1-2013-gold.pdf > (table 1) > > I have done a lot of research and have read that pdftables 0.0.4 is an > excellent way to scrape tabular data from PDF'S (see > https://blog.scraperwiki.com/2013/07/pdftables-a-python-library-for-getting-tables-out-of-pdf-files/ > ). > > I downloaded pdftables 0.0.4 (see https://pypi.python.org/pypi/pdftables). > > I am new to Python and having trouble finding good documentation for how > to use this library. > > Has anybody used pdftables before that could help me get started or point > me to the ideal library for scrapping the PDF links above? I have read that > different PDF libraries are used depending on the format of the PDF. What > library would be best for the PDF formats above? Knowing this will help me > get started, then I can write up some code and ask further questions if > needed. > > Thanks in advance for your help! > > ~Chris > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] PDF Scrapping
Hi, I am looking for the best way to scrape the following PDF's: (1) http://minerals.usgs.gov/minerals/pubs/commodity/gold/mcs-2015-gold.pdf (table on page 1) (2) http://minerals.usgs.gov/minerals/pubs/commodity/gold/myb1-2013-gold.pdf (table 1) I have done a lot of research and have read that pdftables 0.0.4 is an excellent way to scrape tabular data from PDF'S (see https://blog.scraperwiki.com/2013/07/pdftables-a-python-library-for-getting-tables-out-of-pdf-files/ ). I downloaded pdftables 0.0.4 (see https://pypi.python.org/pypi/pdftables). I am new to Python and having trouble finding good documentation for how to use this library. Has anybody used pdftables before that could help me get started or point me to the ideal library for scrapping the PDF links above? I have read that different PDF libraries are used depending on the format of the PDF. What library would be best for the PDF formats above? Knowing this will help me get started, then I can write up some code and ask further questions if needed. Thanks in advance for your help! ~Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ssh socks proxy
Adam Gold adamg...@lavabit.com wrote: I'm trying to write a 'simple' script that will set up a socks proxy over ssh and maintain the connection until manually terminated. It's not possible to use key-based authentication so a password will need to be supplied. Also, note, the user is presented with a list of servers to choose from at the beginning. The actual ssh command is: 'ssh -vNCD 2 user@host'. I've been tinkering with both pexpect and paramiko but fear I'm making a mountain out of a mole hill. I'm aware both have example scripts for ssh forwarding but, to be honest, they are both too complicated (aka I don't know how to customise them). Here is one script I've attempted to get working and the associated error listing: http://pastebin.com/jj8Fgvwm - script http://pastebin.com/jRA8zpzi - error Could anyone help me either correct the script I've started or suggest an ockham's-razor-adherent alternative! Many thanks. The error message indicates that there hostname HOST could not be resolved. You need to replace that with the value of the variable HOST. COMMAND = ssh -vNDR 2 {}@{}.format(USER, HOST) I'm curious to know why you can't use keys. They make things much simpler. -- regards, kushal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ssh socks proxy
kushal.kumaran+pyt...@gmail.com wrote: Adam Gold adamg...@lavabit.com wrote: I'm trying to write a 'simple' script that will set up a socks proxy over ssh and maintain the connection until manually terminated. It's not possible to use key-based authentication so a password will need to be supplied. Also, note, the user is presented with a list of servers to choose from at the beginning. The actual ssh command is: 'ssh -vNCD 2 user@host'. I've been tinkering with both pexpect and paramiko but fear I'm making a mountain out of a mole hill. I'm aware both have example scripts for ssh forwarding but, to be honest, they are both too complicated (aka I don't know how to customise them). Here is one script I've attempted to get working and the associated error listing: http://pastebin.com/jj8Fgvwm - script http://pastebin.com/jRA8zpzi - error Could anyone help me either correct the script I've started or suggest an ockham's-razor-adherent alternative! Many thanks. The error message indicates that there hostname HOST could not be resolved. You need to replace that with the value of the variable HOST. COMMAND = ssh -vNDR 2 {}@{}.format(USER, HOST) I'm curious to know why you can't use keys. They make things much simpler. Excuse the incorrect ssh command. New mail client tripped me up. -- regards, kushal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Saved the Day
I worked on a large pharma sales data warehouse project and we had the need to profile some complex 3rd party data feeds that were poorly documented. I was able to write, test, and run the code (across 500Gb data) to provide the required profiling information in less time than it took to install an evaluation version of a commercial product ... which after several weeks of extensive testing (and hundreds of man hours) never produced the correct results. It amazes me what can done with simple Python scripts and a KISS attitude. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Personal: Re: Tutor Digest, Vol 90, Issue 97
Hi Frank, Please don't unsubscribe. Book reviews are always welcome. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Object designer applications - are there any?
Stephen, You might check out the SQL management tools from Embarcadero. They may provide some of the conversion capabilities you are looking for. And they generate beautiful documentation. Perhaps you could wrap the features of this product with Python scripts to acheive your goals? Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators
Steven, Here's my cheap introduction to decorators... Beautifully explained! Thank you, Malcolm (not the OP) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Excited about python
Dive into Python: http://diveintopython.org/ is what you're looking for. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Excited about python
For a handy reference, you can't beat Python Essential Reference by David Beazley (along with the online documentation, of course!). I think this book is obligatory if you are going to be working with Python a lot. I own all four editions :) But you wanted something more in depth with algorithms, etc. The O'Reilly book Programming Python by Mark Lutz is a classic and is probably a good bet for you. Core Python by Wesley Chun is also good, and I've seen him on this list from time to time. +1 on all of Chris's recommendations with a special +1 for Mark Lutz's book. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] accessing another system's environment
Bill, Coming into this thread late: If you are working with Windows workstations, try posting your question on the Python Windows API mailing list. http://mail.python.org/mailman/listinfo/python-win32 You may be able to use WMI (via Python) to accomplish what you're trying to do. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter, create widgets during runtime?
Elwin, There is a dedicated Python Tkinter mailing list called tkinter-discuss. I would post your question to this mailing list - I've found them very helpful. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing Python Script to read battery level
FT, Is there a way to read the battery level using Python? Check out the following code snippet: Get info on power/battery status http://nullege.com/codes/show/src@jaraco.windows-1.6@jaraco@wind...@power.py/14/ctypes.wintypes.BOOL This code snippet requires the following 3rd party packages: 1. Mark Hammond's pywin32 (comes bundled with ActiveState versions of Python) https://sourceforge.net/projects/pywin32/ 2. Tim Golden's wmi (requires pywin32) http://timgolden.me.uk/python/wmi.html There's also a Python mailing list dedicated to Windows API questions: http://mail.python.org/mailman/listinfo/python-win32 Good luck! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Choice of Python
Marc/Emile, If you're looking for a good hosting service that supports Python, I strongly recommend webfaction.com. I've worked with a lot of hosting companies and webfaction gets my highest endorsement: Great support, helpful user community, very flexible support for hosting Python applications from vanilla CGI to WSGI to Python web frameworks with long running processes such as Django, CherryPy, web2py, etc, and the latest versions of Python. Most of the hosting companies I've investigated support older versions of Python and only support CGI access. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] vim as a python editor; FOLLOW-UP QUESTION
Joel, One more question: IDLE does not appear to have a way to review your command history, e.g., by hitting the up arrow. To move through your command history, use Alt+P (previous) and Alt+N (next). Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] %T as a strftime format identifier
32-bit Python 2.7 for Windows: import time time.strftime(%T) Traceback (most recent call last): File pyshell#97, line 1, in module time.strftime(%T) ValueError: Invalid format string Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple counter to determine frequencies of words in a document
it is difficult for me not to be profuse in my thanks because you guys really go beyond the call of duty. I love this list. The responses in this list most of the times don't just address the problem at hand but are also useful in a more general sense and help people become better programmers. So, thanks for all the good advice as well as helping me solve the particular problem I had. Not the OP, but a big +1 from me! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Too different 2.6 vs 2.7?
Jorge, Python 2.7 supports an updated version of the Tkinter GUI framework with support for native themes (ttk). This makes it possible to create professional looking user interfaces without having to install a separate GUI framework like wxPython or pyQt. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem with python
I just wanted to note that Steven is a great teacher! +1 Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where to start with Unit Testing
Mac, My answer falls in the category feedback ... I'm not the OP, but I wanted to let you know that I really enjoyed your feedback - excellent writeup! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] web-based python?
Alex, I have an IPowerWeb.com server, which claims to support Python Many hosting providers claim to support Python. The best hosting service I've found for Python is webfaction.com. Originally this hosting provider specialized in just Python hosting and this enthusiasm for Python and hands-on Python skills are still part of their culture. Highly recommended. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get script to detect whether a file exists?
Richard, Look at the os.path.isfile function. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives?
Updating this thread for users searching the archives. Additional commentary can be found in this thread I started on Stackoverflow.com. http://stackoverflow.com/questions/3120295/confirm-that-python-2-6-ftplib-does-not-support-unicode-file-names-alternatives Gabriel Genellina added the following comment on Python-list: According to RFC 2640, you should use UTF-8 instead. http://www.faqs.org/rfcs/rfc2640.html The server software must be able to convert from file system encoding to utf-8 and viceversa; check its configuration. The stackoverflow thread mentioned above also contains a workaround/ugly-hack if you need to use Unicode path/file names with ftplib and/or a file server that does not support Unicode path/file names. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Confirm that Python 2.6 ftplib does not support Unicode file names? Alternatives?
Can someone confirm that Python 2.6 ftplib does *NOT* support Unicode file names? Or must Unicode file names be specially encoded in order to be used with the ftplib module? The following email exchange seems to support my conclusion that the ftplib module only supports ASCII file names. Should ftplib use UTF-8 instead of latin-1 encoding? http://mail.python.org/pipermail/python-dev/2009-January/085408.html Any recommendations on a 3rd party Python module that supports Unicode file names? I've googled this question without success[1], [2]. The official Python documentation does not mention Unicode file names[3]. Thank you, Malcolm [1] ftputil wraps ftplib and inherits ftplib's apparent ASCII only support. [2] Paramiko's SFTP library does support Unicode file names, however I'm looking specifically for ftp (vs. sftp) support relative to our current project. [3] http://docs.python.org/library/ftplib.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Not the OP, but I was surprised to see class Name() work (in Python 2.6.5 at least). Is this equivalent to class Name( object ) or does this create an old style class? Going forward into the 2.7/3.x world, is there a preferred style? Thanks, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Hi Mark, I was surprised to see class Name() work (in Python 2.6.5 at least). Is this equivalent to class Name( object ) or does this create an old style class? Going forward into the 2.7/3.x world, is there a preferred style? RTFM? :) I am reading TFM :) Here's why I'm confused. The following paragraph from TFM seems to indicate that old style classes are the default: Quote: For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the “top-level type” object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type() returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are “fixes” that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance. http://docs.python.org/reference/datamodel.html#newstyle Yet TFM for 2.6.5 shows all class examples without specifying a parent class. http://docs.python.org/tutorial/classes.html I've been taught that the proper way to create new style classes has been to always specify an explicit object parent class when creating a new class not based on other classes. Somewhere along the line I seemed to have missed the fact that it is no longer necessary to define classes with 'object' as a parent in order to get a new style class. In other words, it seems that the following are now equivalent: class Name: -AND- class Name( object ): My impression was the class Name: style created an old style class. Thanks for your help! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
In Python 2.x, all classes are old-style unless you directly or indirectly inherit from object. If you inherit from nothing, it is an old-style class regardless of whether you say class Name: pass or class Name(): pass. In Python 3.x, there are no old-style classes. Thanks Steven! Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Steven, Thanks again for your explanations. I thought I had missed a major change in Python class behavior - relieved to find that I'm up-to-date. Cheers, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a class query
Hi Mark, I see that Stephen D'Aprano has already replied twice so I won't bother. Apart from that no offence meant, I hope none taken. Your RTFM reply actually gave me a good laugh. No (zero) offence taken. And I appreciate your many helpful posts in these forums. Cheers, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] portability of pickle and shelve across platforms and different python versions?
Garry, I asked a similar question on Stackoverflow.com and got some great responses including at least one from a member of the Python development team. Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other) http://stackoverflow.com/questions/2003693/best-way-to-save-compl ex-python-data-structures-across-program-sessions-pickle To cut-to-the-chase: I believe pickle files are portable across platforms and versions. I do not know how portable shelve files are. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Iterating through a list of strings
Agreed that line = line[:line.index('%')] is slightly more readable than line = line.split('%', 1)[0] How about: line = line.partition('%')[0] partition() works even if '%' isn't present. The index() and split() techniques raise exceptions if '%' isn't present. Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encoding
Or, maybe even better, the format could be given as third parameter of file open(); then any read or write operation would directly convert from/to the said format. What do you all think? See the codecs.open() command as an alternative to open(). With all the hassles of encoding, I'm puzzled why anyone would use the regular open() for anything but binary operations. Malcolm - Original message - From: spir denis.s...@gmail.com To: Python tutor tutor@python.org Date: Sun, 7 Mar 2010 14:29:11 +0100 Subject: Re: [Tutor] Encoding On Sun, 7 Mar 2010 13:23:12 +0100 Giorgio anothernetfel...@gmail.com wrote: One more question: Amazon SimpleDB only accepts UTF8. [...] filestream = file.read() filetoput = filestream.encode('utf-8') No! What is the content of the file? Do you think it can be a pure python representation of a unicode text? uContent = inFile.read().decode(***format***) process, if any outFile.write(uContent.encode('utf-8')) input --decode-- process --encode-- output This gives me an idea: when working with unicode, it would be cool to have an optional format parameter for file.read() and write. So, the above would be: uContent = inFile.read(***format***) process, if any outFile.write(uContent, 'utf-8') Or, maybe even better, the format could be given as third parameter of file open(); then any read or write operation would directly convert from/to the said format. What do you all think? denis -- la vita e estrany spir.wikidot.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bowing out
Hi Kent, Your posts and web pages really helped me during my early days with python. Wishing you great success in your new endeavors!!! Cheers, Malcolm ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Tutorials: How to create useful programs after learning the syntax?
Wesley, You mean my check is not in the mail? Damn! Well, no more positive reviews for you :) Since you've stepped off your soapbox, I'll also mention your free hour long video hosted by Safari Books (you may have to signup for a free account to see the video). What is Python by CPP (Core Python Programming) by author Wesley Chun http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcasts.php QUOTE: This one-hour webcast is ideal for technical professionals, programmers, engineers or students already literate in another high-level language that want to pick up Python as quickly as possible. No computer science background is necessary. In this webcast, leading Python developer and trainer, Wesley Chun, will help you learn Python quickly and comprehensively so you can immediately succeed with any Python project. Instead of focusing on creating applications, he will address the fundamentals of the language itself. I'm happy to hear about the errata - do you have a link? Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Tutorials: How to create useful programs after learning the syntax?
but if you ever come across a copy of Core Python Programming, i've put lots of exercises at the end of every chapter. +1 from a reader/customer (vs. the author) Core Python Programming is an excellent resource for learning Python. I enjoyed the exercises - they force you to master the content vs. thinkingg you know what's going on via a fast skim of the content. Highly recommended! Regards, Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mac os x executable
Alan, After all with Python 2.3 pre installed on MacOS X Is Python 2.3 really the most recent version of Python distributed with new Macs? So if I wanted to distribute a Python 2.6 script to a Mac user, I would need to instruct the Mac user how to download and install a separate version of Python (2.6), being careful not to overwrite the system default version of Python (2.3). Or I could use py2app to build in single standalone distributable (with an embedded Python 2.6 interpreter and library files) and distribute that. Does that sound right? Thank you, Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] reading and processing xml files with python
Hi, I am a total python XML noob and wanted some clarification on using python with reading remote XML data. All examples I have found assumes the data is stored localy or have I misunderstood this? If I browse to: 'user:passw...@domain.com/external/xmlinterface.jsp?cid=xxxresType=hotel200631intfc=wsxml=' This request returns a page like: HotelAvailabilityListResults size=25 − Hotel hotelId134388/hotelId nameMilford Plaza at Times Square/name address1700 8th Avenue/address1 address2/ address3/ cityNew York/city stateProvinceNY/stateProvince countryUS/country postalCode10036/postalCode airportCodeNYC/airportCode lowRate155.4/lowRate highRate259.0/highRate rateCurrencyCodeUSD/rateCurrencyCode latitude40.75905/latitude longitude-73.98844/longitude + shortDescription lt;bgt;Location.lt;/bgt;lt;brgt; lt;ULgt;lt;LIgt;The Milford Plaza is located in New York, N.Y. /shortDescription thumbNailUrl/hotels/thumbs/NYC_MILF-exter-1-thumb.jpg/thumbNailUrl supplierTypeH/supplierType locationTIMES SQUARE/THEATER DISTRICT/location propertyRating2.5/propertyRating propertyType1/propertyType marketingLevel1/marketingLevel hasMaptrue/hasMap hotelInDestinationtrue/hotelInDestination referenceProximityDistance3.9202964/referenceProximityDistance referenceProximityUnitMI/referenceProximityUnit + HotelProperty specialRateN/specialRate promoDescription72 Hour Sale - Donapos;t miss this great deal!/promoDescription promoType/ promoDetailText/ hrnQuoteKey17A828141014136319/hrnQuoteKey currentAllotment-1/currentAllotment propertyId25033/propertyId propertyAvailabletrue/propertyAvailable propertyRestrictedfalse/propertyRestricted roomDescriptionStandard room/roomDescription roomTypeCode108606/roomTypeCode rateCode252427/rateCode − RateInfo displayCurrencyCodeUSD/displayCurrencyCode − DisplayNightlyRates size=2 displayNightlyRate259.0/displayNightlyRate displayNightlyRate259.0/displayNightlyRate /DisplayNightlyRates displayRoomRate575.76/displayRoomRate chargeableRoomRateTotal575.76/chargeableRoomRateTotal chargeableRoomRateTaxesAndFees57.76/chargeableRoomRateTaxesAndFees nativeCurrencyCodeUSD/nativeCurrencyCode − NativeNightlyRates size=2 nativeNightlyRate259.0/nativeNightlyRate nativeNightlyRate259.0/nativeNightlyRate /NativeNightlyRates nativeRoomRate575.76/nativeRoomRate rateFrequencyB/rateFrequency /RateInfo − PromoRateInfo displayCurrencyCodeUSD/displayCurrencyCode − DisplayNightlyRates size=2 displayNightlyRate155.4/displayNightlyRate displayNightlyRate155.4/displayNightlyRate /DisplayNightlyRates displayRoomRate368.56/displayRoomRate chargeableRoomRateTotal368.56/chargeableRoomRateTotal chargeableRoomRateTaxesAndFees57.76/chargeableRoomRateTaxesAndFees nativeCurrencyCodeUSD/nativeCurrencyCode − NativeNightlyRates size=2 nativeNightlyRate155.4/nativeNightlyRate nativeNightlyRate155.4/nativeNightlyRate /NativeNightlyRates nativeRoomRate368.56/nativeRoomRate rateFrequencyB/rateFrequency /PromoRateInfo /HotelProperty /Hotel I got this so far: import urllib2 request = urllib2.Request('user:passw...@domain.com/external/xmlinterface.jsp?cid=xxxresType=hotel200631intfc=wsxml=') opener = urllib2.build_opener() firstdatastream = opener.open(request) firstdata = firstdatastream.read() print firstdata HotelAvailabilityListResults size='25' Hotel hotelId134388/hotelId nameMilford Plaza at Times Square/name address1700 8th Avenue/address1 address2/ address3/ cityNew York/city stateProvinceNY/stateProvince countryUS/country postalCode10036/postalCode ... I would like to understand how to manipulate the data further and extract for example all the hotel names in a list? Thank you Marti ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Handling Generator exceptions in Python 2.5
I have a generator as follows to do list calculations. *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* The above generator, throws '*ZeroDivisionError*' exception if ListA[i] = 0. Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within that statement)'. Sorry if this question sounds too stupid. TIA Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Handling Generator exceptions in Python 2.5
Thanks everyone for the responses. - Joe On Fri, Jun 19, 2009 at 11:09 AM, vince spicer vinces1...@gmail.com wrote: Well* *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))*if not ListA[i] == 0*] will exclude any results where listA[i] is 0, if you still want these in the result you may want to use good'ol for statement instead of list comprehension results = [] for x in range(len(listA)): y = ListA[i] - ListB[i-1] if not ListA[i] == 0: y = y / ListA[i] results.append(y) print results Vince On Fri, Jun 19, 2009 at 8:55 AM, Joe Python jopyt...@gmail.com wrote: I have a generator as follows to do list calculations. *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]* The above generator, throws '*ZeroDivisionError*' exception if ListA[i] = 0. Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within that statement)'. Sorry if this question sounds too stupid. TIA Joe ___ 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] Best Python Editor
Alan, I spoke a wee bit too soon. The editor is nice but the debugger and some of the other tools windows (eg variables) are broken. Pity, lots of potential here. The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best Python Editor
The current release of Pyscripter is not stable. Drop back one release and you'll find a very solid product. Sounds interesting. What is the stable version and where can it be found? Ken, Here's the version we use: Version 1.7.2, Oct 2006 http://mmm-experts.com/Downloads.aspx?ProductId=4 The most current release (w/2.6.x and 3.x support) can be found here: http://code.google.com/p/pyscripter/ We tried running newer releases earlier this year and had lots of problems. The very latest versions on code.google may be better, but we haven't looked at them. I am interested in hearing feedback on anyone running the most recent release of Pyscripter. Malcolm . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clean text
Denis, Untested idea: 1. Fill a dict with pre-calculated repr() values for chars you want to replace (replaceDict) 2. Create a set() of chars that you want to replace (replaceSet). 3. Replace if (n 32) ... test with if char in replaceSet 4. Lookup the replacement via replaceDict[ char ] vs. calculating via repr() 5. Have result = list(), then replace result += char with result.append( char ) 6. Return ''.join( result ) Does this help? Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clean text
Denis, Thank you for sharing your detailed analysis with the list. I'm glad on didn't bet money on the winner :) ... I'm just as surprised as you that the regex solution was the fastest. Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pythonic way to normalize vertical whitespace
Note: Following cross-posted to python-list where it got queued due to suspicious subject line. I'm looking for suggestions on technique (not necessarily code) about the most pythonic way to normalize vertical whitespace in blocks of text so that there is never more than 1 blank line between paragraphs. Our source text has newlines normalized to single newlines (\n vs. combinations of \r and \n), but there may be leading and trailing whitespace around each newline. Approaches: 1. split text to list of lines that get stripped then: a. walk this list building a new list of lines that track and ignore extra blank lines -OR- b. re-join lines and replace '\n\n\n' wth' \n\n' until no more '\n\n\n' matches exist 2. use regular expressions to match and replace whitespace pattern of 3 or more adjacent \n's with surrounding whitespace 3. a 3rd party text processing library designed for efficiently cleaning up text Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] importance of Docstring
Albert, That was a great writeup on docstrings. I'm going to share that with my dev team. Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Yet another Python book
Dave, Great stuff!!! Thanks for sharing your hard work with the community! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Possible to change values of scalar function parameters?
Is there a way to change values of scalar function parameters? I know you can change the values of parameters if the parameter is a mutable type like a list, but is there a way to update the value of scalar parameters of type integer or string? Simple example: Is there a way to have the following function update its changeme parameter in a 'call by reference' manner? def test1( changeme ): changeme = 'Changed!' ref_value = 'blah' test1( ref_value ) ref_value 'blah' Thanks! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Possible to change values of scalar function parameters?
Kent, No, not a simple way at least. Possibly you can do it with hackery involving stack frames but I wouldn't recommend that. Either pass the values in some kind of container (list, dict, class instance) or return the new value and assign it in the caller. That's what I thought. Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Possible to change values of scalar function parameters?
Alan, But don't forget that in python you can return multiple values from a function. Yes. Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
Lie, The import from __future__ print_function happens automatically in our environment and I took this for granted. Sorry about the confusion :) Regards, Malcolm - Original message - From: Lie Ryan lie.1...@gmail.com To: pyt...@bdurham.com Cc: tutor@python.org Date: Wed, 11 Feb 2009 23:16:11 +1100 Subject: Re: [Tutor] Simple PassGen On Wed, Feb 11, 2009 at 2:26 AM, [1]pyt...@bdurham.com wrote: Are you sure it isn't python 3.x you're playing with? The reason why simple print function works in python 2.x is because of a syntactical coincidence, it is still a 100% statement. Yes, I'm sure :) I restarted IDLE and pasted my session output below: snip You didn't tell that you imported __future__'s print_function! I thought I was having a hallucination or something... seeing that behavior in python2.6 References 1. mailto:pyt...@bdurham.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
Kent, Except they are not equivalent when you want to print more than one thing. ... Python 2.6: In [1]: print(3, 4) (3, 4) I'm running Python 2.6.1 (32-bit) on Windows XP. I don't get the tuple-like output that you get. Here's what I get: print( 3, 4 ) 3 4 Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple PassGen
DOH! I just realized why we're getting different results. Sorry for the confusion - I wasn't trying to be a smart-ass! We've been trying to future proof our new code for Python 3.x so we automatically have 3.0 print() functionality enabled in our Python 2.6 dev environments. Malcolm - Original message - From: spir denis.s...@free.fr To: tutor@python.org Date: Tue, 10 Feb 2009 16:35:26 +0100 Subject: Re: [Tutor] Simple PassGen Le Tue, 10 Feb 2009 10:26:54 -0500, pyt...@bdurham.com a écrit : IDLE 2.6.1 from __future__ import print_function print( 3, 4 ) 3 4 lol! -- la vida e estranya ___ 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] Psyco module
It only runs on Intel 386-compatible processors. Once we know what CPU you are using then we can figure it out better. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sorting Dictionary of Dictionary by certain Value
Hi Pythonistas, I have a large dictionary of dictionary (50,000+ keys) which has a structure as follows: DoD = { 'flintstones' : { 'husband' : fred, 'pal' : barney, 'income': 500, }, 'jetsons' : { 'husband' : george, 'wife' : jane, 'his boy' : elroy, 'income': 700, }, 'simpsons' : { 'husband' : homer, 'wife' : marge, 'kid' : bart, 'income': 600, }, }; I want to sort the dictionary by 'income' Is there an efficient way to do the same. Thanks in advance. - Jo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Confused about import Numeric vs import numpy for Arrays
Hi Everyone, I would like to create a two-dimensional array but am confused as to how to go about it. I've read about Numeric Python and Numpy. Are they one and the same? Also, how do I install them? I am working on a Windows machine. I've been getting the following error messages: import Numeric Traceback (most recent call last): File pyshell#3, line 1, in module import Numeric ImportError: No module named Numeric from Numeric import * Traceback (most recent call last): File pyshell#4, line 1, in module from Numeric import * ImportError: No module named Numeric I then downloaded and installed release 1.1.1 of the Numpy package from this site: http://sourceforge.net/project/showfiles.php?group_id=1369package_id=175103 After restarting the shell, I still get the same errors above (though I do have this directory now: C:\Python25\Lib\site-packages\numpy). Anyone know how to correctly install and use this package? Thanks in advance. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confused about import Numeric vs import numpy for Arrays
No, they are not the same. Numeric is older; NumArray is another older package. You should use Numpy if you can. http://numpy.scipy.org/#older_array snip Now you should be able to import numpy. Kent Thanks, Kent. I ended up using: from numpy import * I wasn't sure what the difference was between this and import numpy Thanks! Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confused about import Numeric vs import numpy for Arrays
In general from module import * is a very bad idea. import module imports a module into its own namespace (e.g., to access its functionality you would have to do module.foo() and module.bar() The form that you chose to use imports all of a module's contents into the current namespace. This means you can call foo() and bar() directly, but it also means that if you have coded a foo() and a bar() you will not have access to the functions in the module you just imported. Timothy, Thanks for the clarification. I had always wondered what the difference was. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confused about import Numeric vs import numpy forArrays
A useful tip is that if you have a long module name you can also use import module as shortname eg import numpy as n and then access numpy.foo() as n.foo() Sacves a lot of typing for a slight loss of clarity in maintenance - you have to remember which module the short names refer to! I tend to use full names in real code and use the abbreviated form when using the prompt. Alan - Great suggestion! As I'm reading through the numpy documentation, there are a lot of great functions that I'd like to learn to use so your advice definitely helps. I was getting tired of constantly having to type numpy.array or numpy.ones all the time. Thanks again. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confused about import Numeric vs import numpy for Arrays
Another reason not to use from xx import * is that it can make it very difficult to discover where a name is defined. If you have several from xx import * lines and then later you use a function foo() there is no easy way to tell which module foo came from. An alternative is to list just the names you want to import: from xx import foo Kent Kent - Another great point. Thanks for contributing to the list. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading List from File
Hi Everyone, I am trying to read a comma-delimitted list (aaa,bbb,ccc) from a text file and assign those values to a list, x, such that: x = [aaa, bbb, ccc] The code that I have come up with looks like this: x = [] f = open(r'c:\test.txt', 'r') x.extend(f.readlines()) x ['aaa,bbb,ccc'] If you look closely, there is an extra pair of single quotes (') that encapsulates the string. Therefore, len(x) returns 1, instead of 3. Is there a function to separate this list out? I hope my question makes sense. Thanks in advance. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Hi Everyone, Thanks for the variety of responses in such a short amount of time. This distribution list is incredible. Sorry for the delayed reply as I wanted to test what everyone suggested, so here goes: --- @Amin: I tried your suggestion, but perhaps I don't understand your syntax. Here is what I tried and the resulting error message: f = open(r'C:\test.txt', 'r') foo = f.readline.split(',') Traceback (most recent call last): File pyshell#16, line 1, in module foo = f.readline.split(',') AttributeError: 'builtin_function_or_method' object has no attribute 'split' Do you know what I did wrong? --- @Emad, Brett: Thank you for your solutions. They do exactly what I was looking for. --- @Chad: Thanks for your suggestion. I think I like it best for its simplicity. --- @Emile, Monika, kinuthi: The CSV standard library looks interesting but I am having mixed results in implementing it. For example, it works when I try this: reader = csv.reader(open(r'c:\test.txt', 'rb')) for row in reader: print row ['aaa', 'bbb', 'ccc'] but it fails when I try: import csv myfile = open(r'c:\test.txt', 'r') data = csv.Reader(myfile, delimeter = ',') Traceback (most recent call last): File pyshell#26, line 1, in module data = csv.Reader(myfile, delimeter = ',') AttributeError: 'module' object has no attribute 'Reader' The error looks similar to what I received when I tried Amin's approach. Am I missing something? --- It's interesting to note that for the solutions to work correctly, I had to remove the quotation marks from the input file. Thanks again to EVERYONE who took the time to respond. I appreciate your help. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Monika, Thanks for your help. I got it to work using the following (also had to spell delimiter): import csv myfile = open(r'c:\test.txt', 'r') data = csv.reader(myfile, delimiter=',') print data _csv.reader object at 0x00D41870 for item in data: print item ['aaa', 'bbb', 'ccc'] I think it was referred to in another post, but I have found this page to be helpful: http://docs.python.org/lib/csv-examples.html Thanks. Samir On Thu, Jul 31, 2008 at 2:20 PM, Monika Jisswel [EMAIL PROTECTED] wrote: oops it is reader not Reader (all lower case), so this line : data = csv.Reader(myfile, delimeter = ',') should be data = csv.reader(myfile, delimeter = ',') 2008/7/31 S Python [EMAIL PROTECTED] Hi Everyone, Thanks for the variety of responses in such a short amount of time. This distribution list is incredible. Sorry for the delayed reply as I wanted to test what everyone suggested, so here goes: --- @Amin: I tried your suggestion, but perhaps I don't understand your syntax. Here is what I tried and the resulting error message: f = open(r'C:\test.txt', 'r') foo = f.readline.split(',') Traceback (most recent call last): File pyshell#16, line 1, in module foo = f.readline.split(',') AttributeError: 'builtin_function_or_method' object has no attribute 'split' Do you know what I did wrong? --- @Emad, Brett: Thank you for your solutions. They do exactly what I was looking for. --- @Chad: Thanks for your suggestion. I think I like it best for its simplicity. --- @Emile, Monika, kinuthi: The CSV standard library looks interesting but I am having mixed results in implementing it. For example, it works when I try this: reader = csv.reader(open(r'c:\test.txt', 'rb')) for row in reader: print row ['aaa', 'bbb', 'ccc'] but it fails when I try: import csv myfile = open(r'c:\test.txt', 'r') data = csv.Reader(myfile, delimeter = ',') Traceback (most recent call last): File pyshell#26, line 1, in module data = csv.Reader(myfile, delimeter = ',') AttributeError: 'module' object has no attribute 'Reader' The error looks similar to what I received when I tried Amin's approach. Am I missing something? --- It's interesting to note that for the solutions to work correctly, I had to remove the quotation marks from the input file. Thanks again to EVERYONE who took the time to respond. I appreciate your help. Samir ___ 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 maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Emile, Amin: Thank you both for your replies. I was able to get it working using: f = open(r'c:\test.txt', 'r') foo = f.readline().split(',') Samir On Thu, Jul 31, 2008 at 3:00 PM, [EMAIL PROTECTED] wrote: Emile is rigth, there should be a () there. I'm sorry, im writing this from my cellphone and there's not a pc around XD. I didn,t know about the csv module either and had to do over complicated things to deal with embedded commas, thx for that too :). -- Amin Rainmaker -- Forwarded message -- From: Emile van Sebille [EMAIL PROTECTED] To: tutor@python.org Date: Thu, 31 Jul 2008 11:34:56 -0700 Subject: Re: [Tutor] Reading List from File S Python wrote: f = open(r'C:\test.txt', 'r') foo = f.readline.split(',') readline is the function/method name readline() executes that function/method and returns a value try typing in 'type(f.readline)' vs 'type(f.readline())' you can't .split() a function but you may split its return value. but it fails when I try: import csv myfile = open(r'c:\test.txt', 'r') data = csv.Reader(myfile, delimeter = ',') Python is case sensitive -- reader is different from Reader. HTH, Emile ___ 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 maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Hi Morgan, Have you installed Python on your computer? If you are using Microsoft Windows, you can download and install Python from here: http://python.org/download/releases/2.5.2/ and select python-2.5.2.msi. Once it's installed, you should have a directory on your machine called C:\python25. If you save your program with a .py extension in that folder (for example, call it morgan.py), then all you have to do is open a command window (Start Run and enter cmd), go to the C:\python25 directory, and type: python morgan.py Personally, if you are just staring out to program, I would recommend using the Python shell that comes with the package I referred to. Alan's tutorial, found here: http://www.freenetpages.co.uk/hp/alan.gauld/ is very helpful, as is this site, which is what I used to start learning Python: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ Hope that helps. Good luck! Samir On Tue, Jul 29, 2008 at 7:27 AM, Morgan Thorpe [EMAIL PROTECTED]wrote: Hello. I'm am very new to the whole programming sence. I am trying to catch on but as soon as i want to write a program i've been told to use like 'notepad' in windows XP and save it as a .py file i have gotten this far. Am i wrong so far? If i am right why is it that i can't run it in anyway besides it opening in 'notepad' i've tried opening with Python but it doesn't work. Thanks, Morgan -- This message has been scanned for viruses and dangerous content by the BCEC Security Gateway, and is believed to be clean. Brisbane Catholic Education however gives no warranties that this e-mail is free from computer viruses or other defects. Except for responsibilities implied by law that cannot be excluded, Brisbane Catholic Education, its employees and agents will not be responsible for any loss, damage or consequence arising from this e-mail. ___ 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] wanting to learn
repost as didn't reply to list first time: 2008/6/12 Michael yaV [EMAIL PROTECTED]: A little background on myself. I am a web designer so I am a Mac person. I have taught myself HTML and flash by reading manuals and a lot of trial and error over the last 11 years. I have always wanted to learn a language like php, asp, .net but I never took the time to learn them. I have recently found Python and believe this is the language that I will hang-my-hat-on and learn. I was web designer a while back, moved into security, then found python, other than that almost the same path as yourself. I don't have any formal training in any coding language but I do have the will to learn. Since my background is web, I want to learn Python and how it relates to the web. I have been told that I need to learn and understand the basics in standard/general Python before I move onto something like django but really, how much Python do I need to know before I can head down the web path? Yes you will need to learn some python but not to the level of taking courses at college/uni straight off the get go. As you learn you will determine what you need as you go on as far as how deep/level the books and tutorials need to be. Don't be like most and put off the super timple tutorials. I had a lot of fun (after reading the Core python books out there) with the kids tutorial because it was just fun to play around and learn some python / work with some python in the process. Honestly I didn't learn anything because the core books taught me everything but if your brain is on information overload then start here: http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ Once you tire of it you can move on to others (still freely available on the web and just a google search away): Non-Programmers Tutorial for Python Official Python Documentation: Text Processing in Python: Python Reference Manual: Python Imaging Library Handbook: How to Think Like a Computer Scientist - Learning with Python: Graphical Programming With Python - QT Edition: Dive Into Python: I had a lot of my first learning from the last, Dive Into Python, and can recommend it, then for books at the bookstore, I bought them all =) but if you only get one, its a tough choice, but wesley chuns core python programming (whatever the latest edition) is a very good book that will dig deep into every corner of python and expose it to you. While you are finish up on these last tutorials and books you'll be already at the level to start playing with django, the online djangobook is free and will help you out a lot. Since I am on an intel/Mac which IDE should I be using? Which one will be robust enough to take me through my journey? I have started with IDLE. IDEs are personal preference and likely to start great debates of opinion back and forth and around again and again ad nauseum. I've run vimtutor like the other poster suggested. However I just didn't use it and got rusty and now will need to run it again. It did not fit my brain well so I just never kept on using it. I know the basics of how to open, edit, save. But all the formatting shortcut keys which I will need are gone. Instead for the command line, you can absolutely not beat iPython shell. Its absolute amazing and you can find tons of free videos on the web showing it off by googling on iPython Tutorial etc. For GUI/IDEs I've tried them all from free to commercial. You can get free versions (cut down in features) of commercial ones like Wing-IDE (good but you need to run it in X11 on Mac) and Komodo IDE (my personal fav), and lots of free ones that may fit your needs / mind (SPE, Eric4, Eclipse with Pyton add-ins, Ulipad, etc. etc.) By far my personal favourites to date will be iPython for terminal, Komodo IDE for GUI IDE with Wing-IDE as a runner up. The final decision you will have is stick with the Apple complied/supplied Python which will lock you out of a few tiny features and lock you into a version without updates for a very long time (in other words until you buy a new version of OS X in most cases). Or you can go to python.org and install the standard framework python (this is my option perference and choice for all my Macs). Other option would be to use Easy Install from PEAK developer tools (google) to help install new modules from the web in egg format. Its a personal choice, its not hard to install modules the standard way (python setup.py install) in python and as a hint if you import the sys module you can use it to tell you all the paths python searches and in there it will show you where the directory is in your Mac for site packages to install all your downloaded modules to. Best of luck, Take it slow and have fun (selecting python gave you the last one, you have to do the first one). PN ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I am a web designer wanting to learn Python
Wesley, Don't be so modest - your Core Python Programming (by Wesley Chun) is also a great book for those looking to learn Python. Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What lib should I use?
On Mon, 26 May 2008 01:51:45 +0200, Julia [EMAIL PROTECTED] said: Hi! I need to write a program what can do two things: 1) get data from the website 2) send information from a textfield (e.g. like a google search) Sounds like you are web scraping or wanting to make a web spider. Check out a) urllib b) urllib2 c) beautifulsoup a + b are built-ins. c you have to download and install from http://www.crummy.com/software/BeautifulSoup/ Cheers, Python Nutter ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] listing classes
Thomas, import types [ name for name in dir(A) if type(eval('A.'+name)) == types.ClassType ] The == types.ClassType doesn't seem to pick out the classes. Also, I think you should be returning eval( name ) vs. name so that the OP gets a list of objects vs. names? (My take on what the poster wanted). Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Why next vs. __next__ ?
Is there a reason why generators have a special method named next vs. __next__? All other Python's special names have the double underscore prefix/suffix. http://docs.python.org/ref/specialnames.html Are there other special names like next that don't have the double underscore delimiters? Thanks! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] When to use % vs. locale.format()?
Are there any best practices guidelines that discuss when one should use % vs. locale.format? The locale.format() seems closer to the new new Python 3.0 print-as-a-function vs. statement ... with the added benefit of localized output. Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] When to use __new__ vs. __init__ ?
Any guidelines on when to use __new__ vs. __init__ when sub-classing? Thanks! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] When to use __new__ vs. __init__ ?
Thanks Kent! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Best practice for installing new packages (eggs)
I would like to take a look at the wxOptParse package. This is my first time installing a package (vs. a module) so I'm looking for feedback on what installation technique I should use and where (in terms of folder paths) one would normally install 3rd party packages. For example, is are there conventions for where to put core packages, experimental packages, and packages that one is building themselves? Also, is it safe to assume that installing a 3rd party package won't (unexpectedly) affect other parts of my Python environment. I'm running Python 2.5.2 on Windows XP Pro SP2. Here are the 3 installation options that wxOptParse provides: snip Choose one of the following methods. In all cases you probably need to run as root. Egg Download # easy_install.py wxoptparse Egg File - # easy_install.py wxOptParse-x.y.z-py2.4.egg Easy Install Zip # easy_install.py wxOptParse-x.y.z.zip Normal Python Install -- # unzip wxOptParse-x.y.z.zip # cd wxOptParse-x.y.z # python setup.py install Also note the following run instructions: If you want to run your program you should be able to type: wxoptparse myprogram.py Under Windows you may need to add c:\Python2.4\scripts to your path (or whatever directory python is installed) in order to run wxoptparse. The standard Python installer does not appear to do this for you. /snip Thank you! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Remove specific chars from a string
Ricardo, Thanks for the tip on how to use maketrans. I was trying to over-complicate things on my side. The string module lives in 3.0 ... only the duplicate methods have been removed. Regards, Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hoping to benefit from someone's experience...
Mark, Here's how we work with RTF: We create a Word document formatted exactly like we want with special markers (unique text) inserted in places where we want to programmatically add text. We save this document to RTF (this RTF becomes our template file), remove all the carriage returns and line feeds, and then replace our marker text with the text we want to insert. Each new version of Word introduces new RTF codes and markup patterns. Recommendation: Find a very old version of Word (Word 95) to generate your RTF 'templates'. The older versions of Word generate much simpler RTF that is forward compatible. Good luck! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Best practice: Use % operator or locale.format?
Does the % operator always respect locale or should one use locale.format() instead? Are there guidelines where one should use one string formatting technique vs. another? Thanks! Malcolm ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Nested, line by line, file reading
Hi everyone, I have a file with this content: 1 1 1 1 1 1 1 2 1 1 I wanted a little script that would print the line containing 2 and every line containing 1 after it. I've tried this: def p(): f = file(prueba.txt,'r') for startline in f.read(): if startline.find(2) != -1: print startline for endline in f.read(): if endline.find(1) != -1: print endline break f.close() p() 2 I found a way for doing it. But still I don't really understand why I don't get two 1 lines printed. It seems that every line is read in for startline f.read() so for endline in f.read() will start reading but find no data, am I right? Thanks, Jon. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python 2.4 or Python 2.5?
Im confused When i had python 2.4 all my scripts work correctly should i reinstall python 2.4? Or should I keep 2.5? Where can I find information on coding for python 2.5? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sys.argv?
I've been reading the python tutorial trying to get used to the style tryna understand it. So I come across this: sys.argv[0] in the tutorial on python.org. What is sys.argv? How does it work? Can someone give me a simple example on how to use it? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] range() help
Alright I'm a bit confused when looking at how range works. I'm reading lesson 4.3 in the python tutorial. http://docs.python.org/tut/node6.html I came across this: range(-10, -100, -30) [-10, -40, -70] How come it prints on -40 or -70. Does -70 come from -70 - -100? This is really confusing me. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Browser based?
How can I used python online. I'm getting my hoster to install python and I'm wondering how Do I use python online? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] celcius to farenheit converter.
I found this site and I'm practicing coding and I write this script, but I'm unsure why its not working. Everything goes well until it gets to the part where it tries to calculate the formula. Inputs work fine anyone know what I did wrong? ### #Temperature Converter #Coding Practice for lamonte(uni-code.com) ### temp = raw_input(Insert a temperature to convert.\n) type = raw_input(Now choose a convertion: Celcius(c) or Farenheit(f)) if type == c: cel = (5/9)*(temp-32) print Farhrenheit +temp+ is equal to +cel+ celcius.\n elif type == f: far = (9/5)*(temp+32) print Farhrenheit +far+ is equal to +temp+ celcius.\n else: print Unknown Syntax!\n; raw_input(\nPress enter to close program) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Some questions.
Hello my name is lamonte and I'm interesting in getting better @ python so I guess this is the correct place then :). One question is whats the best GUI library to build from? Anyone recommend any good tutorials that helped them get good @ learning python? I know some decent basics and soon to try and develope my own game engine. I feel this will be a good project to learn new and different things. Thanks in advanced. Regards, Lamonte Harris. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Accessing class attributes: use methods only?
On Mon, 2007-02-19 at 18:31 -0500, Chris Lasher wrote: I'm used to just setting and getting attributes straight, which would be Pythonic according to Kent and yet also outright wrong according to Alan and academic papers. So is direct access actually not Pythonic, or is it Pythonic and Pythonistas spit in the face of Demeter and her lovely laws? Kent and Alan can speak quite eloquently for themselves, but just to provide a more immediate answer, I expect they mostly agree with each other. The issue isn't whether you code: my.x = 42 or my.setx = 42 Alan is saying you should not generally be twiddling attributes in an object. Kent is suggesting that if you do decide to twiddle attributes in Python, just do it directly. If later on you decide you need some method logic to control the attribute twiddling, you can use property to invoke methods when directly accessing the attribute. I do not think there is anything to be gained in Python by expecting your object interface to depend on the use of get/set methods. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help Please
Hi, This may be too elementary for most of you, but could you please help me with the following question? I would like to use comprehensive lists and lists of lists. Where do I start? Question: Consider a digraph with 10 vertices, labeled 1 through 10. You are given the following adjacency list representation, where we first list the vertices adjacent to vertex 1, and so on. 1*; *2; 2*; *3; 3*; *4; 4*; *5; 5*; *6; 6*; *7; 7*; *8; 8*; *9; 9*; *10; 10. a) Write code to turn the adjacency list into an incidence list and an an adjacency matrix. b) Write code to turn the incidence list into an adjacency matrix. Hint: You may find it useful to note that one incidence list representation is (1*; *1), (2*; *2), (3*; *3), (4*; *4), (5*; *5),(6*; *6), (7*; *7), (8*; *8), (9*; *9), (10*; *10), (1*; *2), (2*; *3), (3*; *4), (4*; *5), (5*; *6), (6*; *7), (7*; *8), (8*; *9), (9*; *10). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help Please
Hi, This may be too elementary for most of you, but could you please help me with the following question? I would like to use comprehensive lists and lists of lists. Where do I start? Question: Consider a digraph with 10 vertices, labeled 1 through 10. You are given the following adjacency list representation, where we first list the vertices adjacent to vertex 1, and so on. 1*; *2; 2*; *3; 3*; *4; 4*; *5; 5*; *6; 6*; *7; 7*; *8; 8*; *9; 9*; *10; 10. a) Write code to turn the adjacency list into an incidence list and an an adjacency matrix. b) Write code to turn the incidence list into an adjacency matrix. Hint: You may find it useful to note that one incidence list representation is (1*; *1), (2*; *2), (3*; *3), (4*; *4), (5*; *5),(6*; *6), (7*; *7), (8*; *8), (9*; *9), (10*; *10), (1*; *2), (2*; *3), (3*; *4), (4*; *5), (5*; *6), (6*; *7), (7*; *8), (8*; *9), (9*; *10). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Redirect from a CGI script
On Sat, 2007-01-20 at 15:22 +, Paulino wrote: Still doesn't work. That's not terribly useful. What status did tamperdata report? What did you see in the browser window? Did you get a 302 status? Try (specify the right URL for your script) telnet localhost 80 GET /cgi-bin/redirect.py enter What do you get? (Describe what happens.) Let us know if you don't understand the telnet command. This should be a server issue, once I use a very basic server: 'from BaseHTTPServer import HTTPServer 'from CGIHTTPServer import CGIHTTPRequestHandler 'HTTPServer((localhost, 80),CGIHTTPRequestHandler).serve_forever() I tryed also with the Karrigel embeded server and nothing happened... I tryed all the sugestions from Andre with no succes. The cgi script as only these two lines: 'print Content-type:text/html\r\n 'print Location:http://python.org/\r\n\r; I have a Win Xp pro machine with Python2.5. Paulino On Sat, 2007-01-20 at 02:10 +, Paulino wrote: Thank you Andre, well it doesn't work either! This works, #!/usr/bin/python print Location:http://python.org/\r\n\r; as does this #!/usr/bin/python print Content-type:text/html\r print Location:http://python.org/\r\n\r; Tested using Apache on Linux. A redirect should have a 3xx status. Apache saw the location header and fixed the status to be 302. My browser (firefox) received the 302 status with the new location and requested the new URL. Each header line should be separated by \r\n. A Python print on linux will only output \n. In actual practice, that appears to work OK. either the browsers tolerate the missing \r or Apache fixes the data stream. Firefox plugins called tamperdata and liveheaders can be very helpful for debugging these kinds of interactions. Get the redirect to a real web site working. Then fix it to redirect to your script. Use tamperdata to see what is going on if you have trouble making it work. Paulino Andre Engels escreveu: 2007/1/18, Paulino [EMAIL PROTECTED]: How can i redirect to another URL from a python CGI script. Is's suposed to be as simply as: print Location : http://newurl It's not working. this simple code does't work - redir.pyw 'print Content-Type:text/html\n\n 'print Location : /cgi-bin/ecodiv.pyw 'print I use CGIHTTPServer, the server script is as follows: 'from BaseHTTPServer import HTTPServer 'from CGIHTTPServer import CGIHTTPRequestHandler 'HTTPServer((localhost, 80), CGIHTTPRequestHandler).serve_forever() instead of redirecting, it only prints 'Location : /cgi-bin/ecodiv.pyw' inthe browser I haven't tested it, but I think I had a similar error recently, and that was solved by removing the \n\n at the end of the Content-Type line. You could try that. -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Redirect from a CGI script
On Sat, 2007-01-20 at 10:13 -0800, Danny Yoo wrote: On Sat, 20 Jan 2007, Paulino wrote: Still doesn't work. [some text cut] I tryed all the sugestions from Andre with no succes. The cgi script as only these two lines: 'print Content-type:text/html\r\n 'print Location:http://python.org/\r\n\r; Ok, good. The last line of the program looks suspicious. If it helps, let me rearrange the program that you've written to: ### print Content-type:text/html\r\n print Location:http://python.org/\r\n; print \r ### The code is missing the critical '\n' that allows the web browser to recognize the header. That gets supplied from the print - doesn't it?. sys.stdout.write(...) would need the final \n and might actually be clearer. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Set changing order of items?
On Fri, 2007-01-19 at 20:05 +, Adam Cripps wrote: On 1/19/07, Simon Brunning [EMAIL PROTECTED] wrote: On 1/19/07, Adam Cripps [EMAIL PROTECTED] wrote: I'm adding strings to a Set to prevent duplicates. However, the strings are meant to be in the correct order. When I add the string to the Set, the order seems to change (and I don't seem to be able to predict what order they are in). Sets, like dictionaries, hold their items in an arbitrary order - see http://tinyurl.com/a2nkg. OK - thanks for that - so it seems that using a Set will complicate the matter more. Really, I want to have a set of sets which won't have any duplicates. An example might look something ilke this: sums = [['1) 10 + 2 =', '12'], ['2) 13 + 4 =', '17']] return sums It looks like you have embedded the numbering into your strings. If the numbers were removed from the strings would you still care about keeping the strings in order? sums = set([('10 + 2 =', '12'), ('13 + 4 =', '17')]) I changed the inside lists of pairs to tuples of pairs for ndx,(query,answer) in enumerate(sums): ... print %d) %s %s % (ndx+1, query, answer) ... 1) 10 + 2 = 12 2) 13 + 4 = 17 How might I achieve this list, without the duplicates (the duplicate bit is the bit I'm stuck on). Adam -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Perfect Python web stack?
On Wed, 2007-01-17 at 16:46 +0200, OkaMthembo wrote: 1) MySQL vs PostGRES PostGRES is a more sophisticated SQL server. It should probably be the default choice. However, I'm primarily using MySQL. The reasons: easy administration - I think supporting dozens of remote databases is easier with MySQL. replication - the loosely coupled MySQL approach to replication has been a better fit for my needs. good performance in the common simple cases You probably need to work through your requirements and match those against the different available products. If you provide a list of requirements, you might get more meaningful feedback. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert a long decimal into a string?
On Tue, 2007-01-16 at 12:28 -0800, Dick Moores wrote: So I go with working up an algorithm for first converting n to an int (for example, multiplying the above n by 1000), converting to a string, putting the decimal point back in between indices 2 and 3, then using that string as n (thereby avoiding the use of quotes around n as the first argument). This seems like a lot of effort for not much reward. Where is n coming from? If you already have something that holds the required level of precision, why does it need to be transformed? Could it already be a string? If n is entered through raw_input, then you received it as a string. I don't want to push you in the wrong direction, but it seems like there must be a better way. -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Length of longest item in a list, using a list comp
On Thu, 2006-12-28 at 11:27 -0800, Tony Cappellini wrote: I want to use a list comp to get the length of the longest string in a list, but can't quite get the syntax right. l1=['abc', 'abcde', 'abcfdtea'] longest=0 [x for x in l1 if len(x) longest] Use max to get the longest longest = max([len(x) for x in ll]) With versions = 2.4 you can omit the [] The problem is I can't add the true clause to the if statement in a list comp as in if len(x) longest: longest = len(x) Is this possible using a list comp? thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Ftp files
On Tue, 2006-12-19 at 07:11 -0800, ray sa wrote: Hi I have just started to learn Python and think it is a superb language. I am faced with an issue that I would like some help with. I need to fetch files on a daliy basis from a unix machine. I would like to run a batch command for this. I would also like to automate this task. The files are stored on the unix box; are hourly files with date and time as the file name. What I would like to do is log in to the relevant directory and fetch the files for that day. I have managed to log in to the ftp site and navigate to the directory where the files are. I have also used the following command to look for a particular day: dateMatch = str(localtime()[0])+str(localtime()[1])+str(localtime ()[2]) This will give me the date portion of the string to search in the file name using: re.search(dateMatch,filename) I am now stuck on how to use the files = listdir(pathName) to get a list of the files and by using the following code: for i in files: matchFile = search(dateMatch,i) if matchFile: get the file What I would like to know is how to get the file using ftplib functions. Your expert advice would be very helpful. Please feel free to suggest some code and an explanation... I need help on the following: -How to get a function to return a list of the files on the directory session = ftplib.FTP(ftpservername) session.login() # supply credentials session.set_pasv(1) # may not be necessary for you file_list = session.nlst() -Using this list I should be able to use the for loop to match the date case and - fetch the files using the get command. How to use the get command to fetch the files in the list prevously where the match was found and store this in my local directory? for f in file_list: # YOU WILL NEED TO ADD YOUR MATCH LOGIC session.voidcmd(TYPE I) # binary transfer size = session.size( f) outname = download.tmp outfile = file(outname,wb) session.retrbinary(RETR + f, outfile.write) outfile.close() mode,ino,dev,nlink,uid,gid,fsize,atime,mtime,ctime = os.stat(outname) if size == fsize: shutil.copy(outname, f) else: # error handling goes here Checking the size may be overkill for your needs. - Also how to run this python file daily automatically? Use a cron job to set this up details. Exact details depend on your flavor of Unix. Looking forward to you responses.. You would almost certainly be better off using SSH (Secure Shell), public keys, and rsync to do this kind of processing. BR Ray __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On Sat, 2006-12-09 at 20:19 +0500, Kamran Haider wrote: Hi I have got some python related queries. I am working on an MRes project which involves a bit of programing in python. Actually, I am using a python program developed by someone, which gives pairwise genetic distances between a set of sequences (I don't know how...) and outputs a simple text file of the following format... s1,s2,s3,s4,s5 4,7,2,3 8,6,4 3,6 7 where s1, s2, s3...represent sequences and the second line describes the pairwise distance between s1 and all other sequences,thid line is for the distance between s2 and other sequences. and so on. 1. I want to read this line into a data structure(most probably by making a list of lists like [[s1,s2,4],[s1,s2,7],[s1,s3,2] and so on) which gives each pair and the corresponding pairwise distances. I think a dictionary will server you better. {(s1,s2):4, (s1,s3):7, (s1,s4):2, } Of course, I would do this by writing a function that reads this file into a data structure which gives the all the pairs of sequences and theircorresponding distance values, but I am not sure how to do this. Well ask for help as you break this down. You should wind up with quite a few functions, not just one. Using a dictionary should be no harder than a list of lists. 2. Secondly, I want to write another function which takes up three arguments, the data structure returned by the previous function and the names of two sequences. It then returns the corresponding value. With the dictionary, this function is trivial def distance(seqdistance, s1, s2): return seqdistance[(s1,s2)] Do you need to handle reversing the sequences? Presumably distance(s1,s2) == distance(s2,s1) Please help Kamran __ Express yourself instantly with MSN Messenger! MSN Messenger Download today it's FREE! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ***SPAM*** List to dictionary
On Thu, 2006-12-07 at 08:22 -0700, Mike Hansen wrote: -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Luke Paireepinart Sent: Wednesday, December 06, 2006 10:54 PM To: tutor@python.org Subject: Re: [Tutor] ***SPAM*** List to dictionary Also, why is there now a **SPAM* in the subject heading? Wonderingly, -Luke Maybe Bill was labeling it SPAM since it was posted twice to the list? shrug / Wed Dec 6 17:00:18 CET 2006 Thu Dec 7 04:31:55 CET 2006 Also, I tried to explain in my reply yesterday. The next statement (temp[i] = 0) is where I get confused. temp is a dictionary. ## earlier code was temp = {} i is a name from a list called names. temp[i] is a reference into the dictionary using i as a key. temp[i] = 0 binds that reference to 0. Any previous value for temp[i] is discarded. temp is simply being used to track distinct names. Any name from names will have one and only one occurrence in the list of dictionary keys. So temp.keys() will contain each name exactly once. As covered in a recent thread, the ordering of the names will probably be different from the original names list. Can someone please explain what is happening here. I'm confused. %) - NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best Known Method for Filtering redundant list items.
On Fri, 2006-12-01 at 11:58 -0800, Chris Hengge wrote: Ok, well... I think people lost the scope of my question.. I'm happy using the first method that was given to my post, I have stated in two emails that the order doesn't matter.. What I asked was why the order was changed, or more directly, what is the command actually doing to my data? I'm sure the order isn't totally random, but based on how the items are checked and dropped. The reason I care is because I'm just nosey like that and what to know what it is doing differently then the method I mentioned in the start of this thread. Your original method stepped through list1 and tested each element for existence in list2. Since you stated that the proportion of duplicates is low, most searches of list2 are unsuccessful and require checking every element of list2 from beginning to end. For long lists the search time adds up. sets and dictionaries are hash based. The location in the collection is based on a hash value. A check for membership computes the hash which is used to pinpoint the location in the collection. There are issues where different elements have identical hashes, but those are handled efficiently. So searching for matches is dramatically faster than stepping through a long list. I believe the ordering within sets and dictionaries happens to match the hash ordering. for x in aset: print hash(x) comes out in ascending order on the 3 sets I checked. That's not really a surprise. In terms of correct programs, the order of set and dictionary items should be viewed as arbitrary. Never did I question the validity of the answer the first reply gave me, it works for what I need, not only that, it works well for what I need. I never put any stipulation on the order of the final data, so I didn't expect an answer that was order related. On 12/1/06, Tor Hildrum [EMAIL PROTECTED] wrote: On 11/30/06, John Fouhy [EMAIL PROTECTED] wrote: For the same reason that dictionaries don't preserve order. Basically, sets are (I think) implemented using a hash table. You can read about hash tables on wikipedia (or many other places), but one of the components of a hash table is a function mapping keys to integers in a particular range. Why not just call a sigar for a sigar. A set is a set, it may be implemented using a hash or it may be implemed using some other datastructure. It could be implemented using lists which preserves order, all though that doesn't make much sense. How it is implemented does not really matter here. http://en.wikipedia.org/wiki/Set If you want a collection of ordered objects, you don't want a set. Not even if the current implementation of sets in Python did preserve order. Doing so could not be considered as anything else than a ugly hack or exploitation of the current implementation. And would be likely to break in the future. Tor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best Known Method for Filtering redundant list items.
On Thu, 2006-11-30 at 12:51 -0800, Chris Hengge wrote: Anyone point me to something more efficient then list2 = list(set(list1)) Older Pythons will force you to import sets and use sets.Set for item in list1: if item not in list2: list2.append() This just seems to take a bit a time when there are thousands or dozens of thousands of records just to filter out the dozen or so copies.. Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best Known Method for Filtering redundant list items.
Right after hitting send I realized I fail to preserver order. If preserving order is important, we're back to using more complex code. On Thu, 2006-11-30 at 16:01 -0500, Python wrote: On Thu, 2006-11-30 at 12:51 -0800, Chris Hengge wrote: Anyone point me to something more efficient then list2 = list(set(list1)) Older Pythons will force you to import sets and use sets.Set for item in list1: if item not in list2: list2.append() This just seems to take a bit a time when there are thousands or dozens of thousands of records just to filter out the dozen or so copies.. Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Linux Distro Anyone
On Tue, 2006-11-28 at 22:45 -0500, Amadeo Bellotti wrote: I was thinking it would be really nice if i could make a Pocket Linux distro that of course fits on one or two floppies (outdated I no but still are amazing) thats just the Linux kernel, bash, and python. with of course a lot of tiny scripts to do daily business and/or recovery. You might want to look at puppyOS. http://www.puppyos.net/ It is designed to boot from USB memory and provides a small footprint OS. http://www.puppyos.net/pfs/ Describes how to build puppy from scratch (pfs) which would allow you to build your own tiny version. We could have a mail client, a text reader/editor, text based web browser, all in python. Of Course this will be a lot of work and it would be neat if the whole user group pitched in. so what I'm basically asking is that if you are interested email me and ill give you some detail. Shooting for a floppy disk based distribution is too much pain with too little gain for me. The puppy approach of a bootable OS that you can carry in your pocket is pretty slick. I'm using a 1 GB USB flash which is, for me, reasonably low cost and far better than carrying floppy disks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What are the issues in running Python script on another machine (developed on Windows but will be using on Linux)
On Sun, 2006-11-26 at 15:14 +, Asrarahmed Kadri wrote: Hi folks, I have a couple of programs that I want to test on a different machine.. I have developed these on Win-XP platform, but I want to test them on my college's machine, which is running Linux. Are there any issues involved or i just need to take my files on a USB memory stick, and copy paste and that is it..? You may need to use dos2unix to convert the DOS/Windows line endings (\r\n) to Unix/Linux/BSD endings (\n) Example usage is: dos2unix myscript.py It's a simple thing to try if you get mysterious errors. thanks for the help. Regards, Asrarahmed -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor