Re: [Tutor] samples on sort method of sequence object.

2010-01-13 Thread Sander Sweers
2010/1/13 Albert-Jan Roskam 
>
> Interesting. Can this also be used to make sorting of alphanumerical list 
> items in a 'numerical' way easier?
> >>> x
> ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 
> 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12']

Yes.
>>> x
['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5',
'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10',
'var_12']
>>> sorted(x, key=lamda x: int(x.strip('var_')))
SyntaxError: invalid syntax
>>> sorted(x, key=lambda x: int(x.strip('var_')))
['var_0', 'var_1', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6',
'var_7', 'var_8', 'var_9', 'var_10', 'var_11', 'var_12', 'var_13',
'var_14']

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Future Appointments...

2010-01-31 Thread Sander Sweers
On 31 January 2010 16:40, Ken G.  wrote:
> Below is a program to determine when my next appointment is.  Line numbers
> are provided for reference only.
>
> 01  import time, datetime, sys
> 02  from datetime import date
> 03  today = date.today()
> 04  print
> 05  print "Today date is:", today
> 06  todaystr = str(today)

You should use today.strftime(), see [1] for the format.

> 07  print
> 08  print "Corrected date format is:",
> 09  print todaystr[ 5: 7], todaystr[ 8:10], todaystr[ 0: 4]

The above then would be. today.strftime('%Y-%m-%d').

> 10  print
> 11  future = raw_input("Next appointment is in how many days?  "),

This will give a string which will need to be converted to a int. You
can do this with int(future). For example d = int(future).

But this might fail if future is a string like b, $ or other non
number string. You can catch the error, see [2] how to do this.

> 12  print
> 13  difference1 = datetime.timedelta(days=1)

When you converted future to an int variable d replace days=1 with days=d.

> 14  datestring = str(today + difference1)

You can use strftime() above.

> 15  print "Next appointment after that is:",datestring
> 16  print
> 17  print "Corrected date format for next appointment is:",
> 18  print datestring[ 5: 7], datestring[ 8:10], datestring[ 0: 4]

Again, strftime() can be used.

> 19  sys.exit()
>
> In answering the question in line 11 as to when is my next appointment, I
> would answer "3" (for 2/3/2010) but how do I change "days=1" at end of line
> 13 to "days=3" so that datestring would read "2010-02-03" instead of
> "2010-02-01" as presented above?

See comments inline also. You will need to convert your raw_input
result future to a number with "int()" and store it in a new variable
wich can be used in datetime.timedelta().

Greets
Sander

[1] http://docs.python.org/library/time.html#time.strftime
[2] http://docs.python.org/tutorial/errors.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] query

2010-01-31 Thread Sander Sweers
On 31 January 2010 22:21, invincible patriot
 wrote:
> can any one tel me how can i do indexing of individual characters in python
> like if i hav a word eg david
> a='david'
> b=list(a)
> # this will give ['d','a','v','i','d']
> not i want to print the index of each character
> how can i do that
> please tel me

Look at http://diveintopython.org/getting_to_know_python/lists.html.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] correcting an Active State Recipe for conversion to ordinal

2010-02-04 Thread Sander Sweers
On do, 2010-02-04 at 13:30 -0500, Serdar Tumgoren wrote:
> Could you all indulge me one last time and tell me if the above
> version works for you? If so, I'll update the recipe to spare others a
> similar headache.

It now works ok but..

You should not use ord as variable as ord() is used by python already.

Also this will fail in python 3 and 2 with import from future, it does
division differently.
>>> from __future__ import division
>>> 11 % 100 / 10
1.1001

So "if value % 100/10 <> 1:" should be "if value < 10 or value > 13:".

greets
Sander

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple variable type question

2010-02-05 Thread Sander Sweers
On vr, 2010-02-05 at 16:54 +, Antonio de la Fuente wrote:
> http://openbookproject.net/thinkcs/python/english2e/ch05.html
> 
> exercise number 3 (slope function) and when I run it:
> 
> python ch05.py -v
> 
> the doctest for the slope function failed, because is expecting a
> floating point value and not an integer:
> 
> Failed example:
> slope(2, 4, 1, 2)
> Expected:
> 2.0
> Got:
> 2

Python handles integers a bit counter intuitive. It does not
automatically converts you devision from an int to a float number. 

>>> 1 / 2
0
>>> 3 / 2
1

You would expect this to become 0.5 and 1.5.

> This is the function, and how I modified so it would return a floating
> point value (multiply by 1.0). But this doesn't feel the right way to
> do things, or is it?

Not is is not, if you would type this into a python shell or idle you
will still fail the 3rd test.

>>> (3-2)/(3-1) * 1.0
0.0

> def slope(x1, y1, x2, y2):
> """
> >>> slope(5, 3, 4, 2)
> 1.0
> >>> slope(1, 2, 3, 2)
> 0.0
> >>> slope(1, 2, 3, 3)
> 0.5
> >>> slope(2, 4, 1, 2)
> 2.0
> """
> result_slope = ((y2 - y1) / (x2 - x1)) * 1.0
> return result_slope

You will need to find a way to convert your int numbers to float numbers
*before* doing the calculation.

Greets
Sander

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple variable type question

2010-02-05 Thread Sander Sweers
On vr, 2010-02-05 at 20:39 +, ALAN GAULD wrote:
> return float(x1-y1)/(x2-y2)

Does not work properly in version 2. Example is the 3rd doc test:
float((3-2)/(3-1)) gives 0.0 instead of 0.5. 

Greets
Sander

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] datetime a.m. not AM

2010-02-08 Thread Sander Sweers
On ma, 2010-02-08 at 13:02 -0800, bevan j wrote:
> data = '1/09/1978 1:00:00 a.m.' 

If you know this will always be in the form of 'a.m.' you can replace it
with 'am' by data.replace('a.m.','am').

Greets
Sander

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rstrip in list?

2010-02-09 Thread Sander Sweers
On Tuesday 09 February 2010 16:28:43 Ken G. wrote:
> ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n']
> 
> I was using 'print mylist.rstrip()' to strip off the '\n'
> 
> but kept getting an error of :
> 
> AttributeError: 'list' object has no attribute 'rstrip'

A string has attribute rstrip not a list.

You will need to loop over the list and update each item of the list with 
rstrip(). This, mylist = [s.rstrip('\n') for s in mylist], should do it.

It might be that before making the list you did rstrip() on the individual 
strings..?

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shelve

2010-02-11 Thread Sander Sweers
On do, 2010-02-11 at 10:09 -0600, Randy Raymond wrote:
> I am running Python 2.6.4 under Windows Vista 32-bit Home Edition.
> When I run:
>  
> import shelve
> test=shelve.open("myTest.fil")

And to shich directory does this file get written? I suspect you are
writing to a protected directory. When no path is given it will be
written to the current directory, check with the os module where this
is.

  import os, shelve
  print os.path.realpath(os.path.curdir)
  test=shelve.open("myTest.fil")

Better is to always pass a full path like, 'C:\\Users\\ I get a DCPermissionerror exception.  I am an administrator on this
> machine (it is my home PC).  Python and Pythonw are both allowed
> exceptions to the Windows firewall.  I tried turning the Windows
> Firewall completely off, but that does not help.  Any ideas?  

It is *always* helpful to provide the full error message.

Greets
Sander


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] command error

2010-02-16 Thread Sander Sweers
On 16 February 2010 21:32, Shurui Liu (Aaron Liu)  wrote:
> Here is a program I wrote, I don't know why I cannot exit when I tried 10
> times? Hope somebody can help me. Thank you!
>
> while (guess != the_number):
>     if (guess > the_number):
>     print ("Lower...")
>     print ("You were wrong, try again", tries, "times left.\n")
>     else:
>     print ("Higher...")
>     print ("You were wrong, try again", tries, "times left.\n")
>
>     guess = int(raw_input("Take a guess: "))
>     tries -= 1

This will loop untill guess == the_number with no other way out.
Meaning unless the number is guessed it will end up in an infinite
loop. You will have to figure out how to *break* out ot the while loop
when tries == 0.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] datetime, time zones, and ISO time

2010-02-17 Thread Sander Sweers
On 17 February 2010 22:37, David Perlman  wrote:
> As far as I can tell, this should always work.  So wouldn't it be nice if
> there were a less convoluted way to get this??

There is pytz [1] which should provide a simpler way to manage
timezone info in python.

Greets
Sander

[1] http://pytz.sourceforge.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is the max size so low in this mail list?

2010-03-01 Thread Sander Sweers
On 1 March 2010 18:13, Wayne Watson  wrote:
> See Subject. 40K here, but other Python lists allow for larger (total)
> sizes.

Don't know but if it is that long use pastebin [1].

Greets
Sander

[1] http://python.pastebin.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread Sander Sweers
On 3 March 2010 14:17, Kent Johnson  wrote:
> After six years of tutor posts my interest and energy have waned and
> I'm ready to move on to something new.

Let me join the other people and thank you for your contribution to
this list. Good luck with something new :-)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-03 Thread Sander Sweers
On 3 March 2010 20:44, Giorgio  wrote:
 s = "ciao è ciao"
 print s
> ciao è ciao
 s.encode('utf-8')
> Traceback (most recent call last):
>   File "", line 1, in 
>     s.encode('utf-8')
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 5:
> ordinal not in range(128)

It is confusing but once understand how it works it makes sense.

You start with a 8bit string so you will want to *decode* it to unicode string.

>>> s = "ciao è ciao"
>>> us = s.decode('latin-1')
>>> us
u'ciao \xe8 ciao'
>>> us2 = s.decode('iso-8859-1')
>>> us2
u'ciao \xe8 ciao'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2010-03-03 Thread Sander Sweers
On 3 March 2010 22:41, Sander Sweers  wrote:
> It is confusing but once understand how it works it makes sense.

I remembered Kent explained it very clear in [1].

Greets
Sander

[1] http://mail.python.org/pipermail/tutor/2009-May/068920.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SQLite error messages

2010-03-09 Thread Sander Sweers
- Original message -
> I am using the sqlite3 module with Python 3.1, and have some code which
> goes something like as follows...
>
> import sqlite3
> con = sqlite3.connect('MyDatabase.db')
>
> try:
>        execresult = con.execute('INSERT INTO MyTable (field_name) VALUES
> ("MyValue")')
>        con.commit()
> except:

Here you catch all exceptions. Normally you would catch a specific exception 
like ValueError.  
>        con.rollback()
>

Do you know finally? It is run after all the exceptions have been handled and 
this is where I would put the rollback.

Greets,
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SQLite error messages

2010-03-10 Thread Sander Sweers
On 10 March 2010 21:02, Alan Harris-Reid  wrote:
> Maybe I have misunderstood you, but I always thought that the 'finally'
> section was run even if the 'try' section is successful, in which case I
> would not want a rollback.

I was thinking something like this.

import sqlite3
con = sqlite3.connect('MyDatabase.db')

execresult = None
try:
execresult = con.execute('INSERT INTO MyTable (field_name) VALUES
("MyValue")')
con.commit()
finally:
if not execresult:
print 'Rollback'
con.rollback()

This way you can have a rollback and still see an exception.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Escaping a single quote mark in a triple quoted string.

2010-03-13 Thread Sander Sweers
On 13 March 2010 18:33, Ray Parrish  wrote:
> Hello,
>
> I am getting the following -
>
 String = """http://www.rayslinks.com";>Ray's Links"""
 String
> 'http://www.rayslinks.com";>Ray\'s Links'
>
> Note the magically appearing back slash in my result string.

It is not really there. When you have a single quote in a single quote
string it need to be escaped with a backslash. Simulary a double quote
in a double quote string. The triple quote string does this for you.

When you write the string to a file the backslash will "magically" disappear.

> Now I tiry to escape the single quote.
>
 String = """http://www.rayslinks.com";>Ray\'s Links"""
 String
> 'http://www.rayslinks.com";>Ray\'s Links'
>
> Once again the unwanted back slash appears.

See above single quotes in single quote string need to be escaped.

 NewString = """'"""
 NewString
> "'"
> Hmmm, no back slash this time...

Correct, here you have a single quote in a double quote string.

 String = """http://www.rayslinks.com";>Ray""" + """'""" + """s
 Links"""
 String
> 'http://www.rayslinks.com";>Ray\'s Links'
>
> Why did quoting the single quote work in NewString when I triple quoted just
> the single quote, but not in the other examples where the result shows a
> back slash before my singe quote in String?
>
> Is there a proper way to do this?

You are trying to solve something that is not really a problem. What
is however is your usage of a single quote in html text. You need to
replace it with ' or ‘.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess

2010-03-27 Thread Sander Sweers
On 27 March 2010 09:30, David Abbott  wrote:
> Here is an example using subprocess.call
> http://dwabbott.com/code/index8.html
>
> and some more here with subprocess.Popen
> http://asterisklinks.com/wiki/doku.php?id=wiki:subprocess

On top of that we have the excelent PyMOTW from Doug on subprocess.
http://blog.doughellmann.com/2007/07/pymotw-subprocess.html

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Move all files to top-level directory

2010-04-12 Thread Sander Sweers
On 12 April 2010 18:28, Dotan Cohen  wrote:
> However, it fails like this:
> $ ./moveUp.py
> Traceback (most recent call last):
>  File "./moveUp.py", line 8, in 
>    os.rename(f, currentDir)
> TypeError: coercing to Unicode: need string or buffer, tuple found

os.rename needs the oldname and the new name of the file. os.walk
returns a tuple with 3 values and it errors out.

Also os.getcwd returns the working dir so if you run it in the wrong
folder you will end up with a mess. In idle on my windows machine at
work this is what is gives me.

>>> os.getcwd()
'C:\\Python26'

So it is better to give the program the path you want it to look in
rather then relying on os.getcwd().

os.walk returns you a tuple with the following values:
(the root folder, the folders in the root, the files in the root folder).

You can use tuple unpacking to split each one in separate values for
your loop. Like:

for root, folder, files in os.walk('your path):
   #do stuff

It might be wise to only have this module print what it would do
instead of doing the actual move/rename so you can work out the bugs
first before it destroys your data.

Hope this helps.
Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Move all files to top-level directory

2010-04-12 Thread Sander Sweers
On 12 April 2010 22:13, Dave Angel  wrote:
> When combining directory paths, it's generally safer to use
>
> os.path.join()

As KDE/Dolphin runs on windows this is even more important as it will
sort out the directory separator (/ vs \) for you.

Some added reading on os.path can be found on Doug's excellent PyMOTW
[1]. Also check out the glob module [2].

Greets
Sander

[1] http://blog.doughellmann.com/2008/01/pymotw-ospath.html
[2] http://blog.doughellmann.com/2007/07/pymotw-glob.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem iterating over csv.DictReader

2010-04-26 Thread Sander Sweers
On 26 April 2010 15:00, Matthew Williams  wrote:
> What I'm looking for is a way to explicity reset the iterator, to tell it to
> go back to the beginning.

You will need to use the seek method on the fileobject.

f = open('insert your csv file here.csv', 'rb') #Note the b in 'rb'

#Do your processing

f.seek(0)

#Do some more

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] For loop breaking string methods

2010-04-26 Thread Sander Sweers
On 26 April 2010 21:38, C M Caine  wrote:
> Why does this not work:
 L = [' foo ','bar ']
 for i in L:
>     i = i.strip()

str.strip() _returns_ a *new* string and leaves the original string
alone. The reason being that string are immutable so can not be
changed.

>>> s1 = ' foo '
>>> s1[1]
'f'
>>> s1[1] = 'g'

Traceback (most recent call last):
  File "", line 1, in 
s1[1] = 'g'
TypeError: 'str' object does not support item assignment

However lists are mutable and can be changed in place.

>>> l = [' foo ','bar ']
>>> l[0] = ' boo '
>>> l
[' boo ', 'bar ']
>>> l[1] = 'far '
>>> l
[' boo ', 'far ']


> But this does:
 L = [i.strip() for i in L]
 L
> ['foo', 'bar']

What you do here is create a *new* list object and assign it to
variable L. The new list is created with *new* string objects returned
by str.strip().

Putting the 2 together you could do something like below but I would
use a list comprehension like you did above:

>>> l = [' foo ','bar ']
>>> for x in range(len(l)):
l[x] = l[x].strip()

>>> l
['foo', 'bar']
>>>

> What other strange behaviour should I expect from for loops?

You should read up on immutable data types like strings and tuples.
Start with [1].

Greets
Sander

[1] http://docs.python.org/reference/datamodel.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] writing csv files

2010-05-22 Thread Sander Sweers
On 22 May 2010 09:46, prasad rao  wrote:
>  csvw=csv.writer(open('/home/prasad/kkm','w'),
> dialect='excel',fieldnames=names)
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: 'fieldnames' is an invalid keyword argument for this function

fieldnames is part of the dictreader and dictwriter objects and you
use the writer object. See the online docs [1] for more info.

Greets
Sander

[1] http://docs.python.org/library/csv.html#csv.DictWriter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Sander Sweers
2010/5/28 spir ☣ :
> his is a different feature from preserving *input* order of of keys, or of 
> key:value pairs.

In Python 2.7 and 3.1 [1] we now have the OrderedDict which does
preserve input order.

Greets
Sander

[1] http://www.python.org/dev/peps/pep-0372/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parse text file

2010-06-03 Thread Sander Sweers
On 3 June 2010 21:02, Colin Talbert  wrote:

> I couldn't find any example of it in use and wasn't having any luck getting
> it to work based on the documentation.


Good examples of the bz2 module can be found at [1].

greets
Sander

[1] http://www.doughellmann.com/PyMOTW/bz2/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for duplicates within a list

2010-06-11 Thread Sander Sweers
On 11 June 2010 15:57, Ken G.  wrote:
> In any event, if a number is listed more than once, I would like to know how
> many times, such as 2 or 3 times.  For example, '3' is listed twice within a
> list.

If you do not have top keep the order of the number this will work.

>>> a = [1, 2, 3, 3, 4]
>>> counted = {}
>>> for n in a:
if not n in counted:
counted[n] = 1
else:
counted[n] += 1

>>> counted
{1: 1, 2: 1, 3: 2, 4: 1}

>>> for x, y in counted.items():
if y > 1:
print "Number %s was found %s times" % (x, y)
else:
print "Number %s was found %s time" % (x, y)

Number 1 was found 1 time
Number 2 was found 1 time
Number 3 was found 2 times
Number 4 was found 1 time

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Linux webcam libraries?

2010-06-13 Thread Sander Sweers
On 12 June 2010 20:22, Wayne Werner  wrote:
> I want to be able to grab a webcam image via python. So I'm curious if
> anyone has had any experience/luck in this particular area and/or knows of
> any libraries I should take a look at. I know my webcam definitely works
> under linux because I can use the cheese program and see the image...

Everything that captures video under linux is managed by video4linux
[1]. You will have to figure out how to use it with python. A quick
google search led me to v4l2capture [2].

Greets
Sander

[1] http://www.linuxtv.org/wiki/index.php/Main_Page
[2] http://pypi.python.org/pypi/v4l2capture/1.2
___
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?

2010-06-24 Thread Sander Sweers
- Original message -
> On Fri, 25 Jun 2010 04:51:13 am Lie Ryan wrote:
> > On 06/24/10 02:10, pyt...@bdurham.com wrote:
> > > 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?
> > 
> > I don't know the specifics about ftplib, however I believe in most
> > file systems, file names are plain byte-strings, i.e. most file
> > systems do not handle encoding, they only deal with plain bytes.
> 
> That is completely backwards. Most modern file systems use Unicode, not 
> bytes.

-snip-

> These days, if you're a developer on a non-Linux PC who doesn't need to 
> worry about legacy file systems, most file systems you come across will 
> be Unicode and not bytes. It's mostly Linux developers who have to deal 
> with byte file names.

Linux filesystems do not store encoding information as part of the filesystem. 
It does not care if you give it an unicode filename or byte filename to write 
to disk. It is up to the userland applications to properly make sense of the 
filename.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] raw_input

2010-07-05 Thread Sander Sweers
On 5 July 2010 17:40, Shashwat Anand  wrote:
> use input() instead of raw_input() in Python3.x

To add to this, in Python 2 we had input() [1] (unsafe for most uses)
and raw_input() [2] (safe). Python 3 removed the old input() and
renamed raw_input() to input() [3,4].

Greets
Sander

[1] http://docs.python.org/library/functions.html#input
[2] http://docs.python.org/library/functions.html#raw_input
[3] http://docs.python.org/release/3.0.1/whatsnew/3.0.html#builtins
[4] http://www.python.org/dev/peps/pep-3111/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help return a pattern from list

2010-07-05 Thread Sander Sweers
On 5 July 2010 19:54, Vineeth Rakesh  wrote:
> Can some one help me to return a special pattern from a list.
>
> say list =
> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>
> now say I just need to return the files with .mp3 extension. How to go about
> doing this?

Use os.path.splitext() to check for the extension and check if it
equals the extension you want. For example like below idle session:

>>> import os
>>> say_list = 
>>> ["something1.mp3","something2.mp3","something4.pdf","something5.odt"]
>>> mp3_list = [x for x in say_list if os.path.splitext(x)[1].lower() == ".mp3"]
>>> mp3_list
['something1.mp3', 'something2.mp3']

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess output

2010-07-28 Thread Sander Sweers
- Original message -
> I'm using Python 2.6.5 and I've got a challenge with the subprocess
> module. I'd like the output to be stored in a variable, and not sent to
> the stdout. The relevant lines as they are now:

Go to google, enter "pymotw subprocess" and hit I am feeling lucky ;-)

greets
Sander

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string to list

2010-08-05 Thread Sander Sweers
On 5 August 2010 06:38, Vikram K  wrote:
> Suppose i have this string:
> z = 'AT/CG'
>
> How do i get this list:
>
> zlist = ['A','T/C','G']

If you know the format of the string is always the same you can do
something like this. This fails when you have strings that do not have
the '/' in the middle and has 2 characters on either side.

def parseString(s):
n = s.find('/')
l = []
if n:
l = [s[0],s[n-1:n+2], s[-1]]
return l

>>> parseString(s)
['A', 'T/C', 'G']

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modify csv textfile

2010-08-07 Thread Sander Sweers
On 7 August 2010 04:35, TGW  wrote:
> I have a pipe delimited text file with 5 columns which looks like this:
> 12345|some text|some more text|example125 oo3 3456|example32423
> 11223|more text|and more|example/73d 77665|example455667
> 12677|text|more|anotherexample 123|anotherexample45
>
> What I want to output is:
> 12345|some text|some more text|example|example32423
> 11223|more text|and more|example|example455667
> ...
> 12677|text|more|anotherexample 123|anotherexample45
>
> So column 4 is where the change occurs, but only if the beginning of the 
> string in column 4  =~ /^example/i  # and it should be case insensitive
>
> #!/usr/bin/env python
> import csv
> import re
>
> filename = raw_input("Enter the filename to edit: ")
>
> reader = csv.reader(open(filename, 'rb'), delimiter='|', 
> quoting=csv.QUOTE_NONE)
> for row in reader:
>    print row
>
> 
> I can print the file, I just need a little help searching and replacing the 
> column 4 data element.

You can test if one item in your list begins with example like:
' example125 oo3 3456'.lstrip()[:7].lower() == 'example'

lstrip() will remove any unwanted white space on the left side of the string.
slice [:7] will give you the first 7 characters from the string.
lower() will make the string lower case so your requirement for case
insensitive is met.

Then your loop would look like (untested):

for row in reader:
if row[3].lstrip()[0:7].lower() == 'example':
 row[3] = row[3].lstrip()[:7] #we replace the fourth item.
print row

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modify csv textfile

2010-08-07 Thread Sander Sweers
On 7 August 2010 13:45, TGW  wrote:
>> You can test if one item in your list begins with example like:
>> ' example125 oo3 3456'.lstrip()[:7].lower() == 'example'
>
> I think I need to use regex here. Perhaps you will agree.

You could but you don't have to, consider this.

r = '1234|Avail|53|Potato Chips and salse'.split('|')
s = 'potato chips'

if r[3].lstrip().lower().startswith(s):
r[3] = r[3].lstrip()[:len(s)]
print r

> Input file:
> 1119|Avail|53|Potato Chips
> 1234|Avail|53|Potato Chips and salse
> 1399|Avail|53|potato chips
> 1445|Avail|64|Pretzels
> 1490|Avail|64|Pretzels and mustard
> etc...
>
> #!/usr/bin/env python
> import csv
> import re
>
> filename = raw_input("Enter the filename to edit: ")
>
> reader = csv.reader(open(filename, 'rb'), delimiter='|', 
> quoting=csv.QUOTE_NONE)
> for row in reader:
>    if re.match('potato chips.*', row[4].lower()):
>        row[4] = 'Potato Chips'
>
>    if re.match('^pretzels.*', row[4].lower()):
>        row[4] = 'Pretzels'
>
>    print row

Python start numbering indexes at 0 so row[4] is the *5th* item item
in your list.

> Row will be variable length, so strip() will not work for me.

I did not use strip() but lstrip() and only to remove leading
whitespace..? However strip only removes the _leading and trailing_
whitespace or character(s) you pass it.

> But neither does my latest attempt ^^

With the info and example data provided this would surely have given
an IndexError. So if you run into an exception you need to provide
them as they will be giving clues where it is going wrong.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Performance list vs. deque for [-1]

2010-08-12 Thread Sander Sweers
On 12 August 2010 09:44, Alan Gauld  wrote:
>> I'm wondering what's the fastet datatype in python to lookup the last
>> element in an ordered collection.
>
> When in doubt timeit()

Out of curiosity I used timeit and lists are faster if we iterate over
them one by one. Now this is my first go with the timeit module so
please do correct me :-). Code used is at
http://python.pastebin.org/475014.

def getLastItem(c):
return [x[-1] for x in c]

The list/deque consists of 5000 items (lists or deques) with a length
21 random ints. Also for deque I used maxlen=26 which makes it a bit
faster.

List took 0.000693 seconds
693.01178383827209 / 10 (default times run by timeit)

Deque took 0.009195 seconds
693.01178383827209 / 10 (default times run by timeit)

How this applies to the OP situation I don't know..

Greets
Saner
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string conversion according to the terminal

2010-08-12 Thread Sander Sweers
On 12 August 2010 10:40, Evert Rol  wrote:
 a = "my file number"
 a.replace(' ', '\\ ')
> 'my\\ file\\ number'

What if a has more than 1 space between words? Then I think this would
be a safer way.

>>> print "\\ ".join("my  file  number".split())
my\ file\ number

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Performance list vs. deque for [-1]

2010-08-12 Thread Sander Sweers
On 12 August 2010 12:07, Sander Sweers  wrote:
> Deque took 0.009195 seconds
> 693.01178383827209 / 10 (default times run by timeit)

Messed up the deque results :(

Deque took 0.009195 seconds
919.49732708930969 / 10 (default times run by timeit)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple file open

2010-08-18 Thread Sander Sweers
On 18 August 2010 17:14, nitin chandra  wrote:
> I am on Python 2.6
>


> Please guide with the syntax.

All beginners tutorials on the web teach the syntax of python.. I am
unsure what your questions is.

> below is the existing program with Formula A (Mean). Formula B will be
> Extrapolation,
> also I have not been able to do justice to 'except IOError:' part.The

It has many errors which need fixing but..

> program ends with an error.

And if you get an error always make sure you provide it to this list.
People on this list can not read minds ;-).

> 
> import sys,os, fileinput
>
>
> file11 = raw_input('Enter PR1 File name :')
> fp1 = open(file11,'r')
>
> file12 = raw_input('Enter PR3 File Name :')
> fp2 = open(file12,'r')
>
> file3 = raw_input('Enter PR2 / PR4 OUTPUT File Name :')
> fp3 = open(file3,'w')

What happens when you enter a wrong filename? It will raise IOError
the moment you use open(). Below is 1 example of what you might want
tot do.

file11 = raw_input('Enter PR1 File name :')
try:
fp1 = open(ffile11, 'r')
except IOError:
   sys.exit('Could not open file: %s' % file11)

> while True:
>   try:
>       line1A = fp1.readline()

You can read and split the line in 1 go.
 line1 = fp1.readline().split(",")

>       line1B = fp2.readline()
>       line1 = line1A.split(",")

You can now remove the above, see earlier comment.

>       col1 = line1[0]
>       col2 = line1[1]
>       col3 = line1[2]
>       col4 = line1[3]
>       col5 = line1[20]
>       col6 = line1[21]
>       col7 = line1[22]
>       line2 = line1B.split(",")
>       col8 = line2[1]
>       col9 = line2[2]
>       col10 = line2[3]
>       col11 = line2[20]
>       col12 = line2[21]
>       col13 = line2[22]

Above you create a list "line1 = fp1.readline().split(",")". Lists are
mutable so you can add, remove and insert new items. You can also
access the items in the list by index. You can even add 2 lists to
make a new list, eg: .

>>> [1,2,3,4,5] + [6,7,8,9,0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Now try and apply this to all your col variables.

>       # calculation of PR2 as per formula
>       #(A+B)/2 , ie. Mean of the two values
>       col14 = ( (float(col2)) + (float(col8)) / 2)

You can write this as:
  col14 = (float(line1[1])) + (float(line2[1])) / 2)

And avoid creating all these col variables. But what would happen if
col2/line1[1] has a value of "I am not a number"? Do note the comment
below on the actual calculation.

>       col15 = ( (float(col3)) + (float(col9)) / 2)

>       col19 = ( (float(col7)) + (float(col13)) / 2)

Your "mean" calculation is wrong (hint, division has precedence over adding).

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding all numbers in a file or list

2010-08-23 Thread Sander Sweers
On 23 August 2010 17:13, aug dawg  wrote:
> Is there a command or module that I can use to add all the items in a list?
> Alternatively, is there one I can use to add all the numbers in a file?

sum() is what you are looking for [1].

Greets
Sander

[1] http://docs.python.org/library/functions.html#sum
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Adding all numbers in a file or list

2010-08-23 Thread Sander Sweers
On 23 August 2010 17:24, aug dawg  wrote:
> So it's sum(list_name) ?

Correct, but it is not limited to lists. Any itterable with
ints/floats will do, for example a tuple is also accepted.

Greets
Sander

PS: Please use reply to all so others on this list may benefit from
the questions/answers ;-)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Controlling a device with ioctl's?

2010-08-24 Thread Sander Sweers
On 25 August 2010 00:04, Joe Veldhuis  wrote:
> Hello to all. I'm working on writing a tool that will control a piece of 
> hardware using ioctl's on its device node. Specifically, I'm trying to 
> configure and tune a DVB-S receiver on Linux.
>
> Just for starters, I want to try opening the frontend and setting the LNB 
> voltage. An example in C:

Maybe you can use the python v4l2 bindings from [1] as example how to
use it for dvb. Not used it or have any experience with anything like
this but it might help..

Greets
Sander

[1] http://pypi.python.org/pypi/v4l2
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] more on wx and tiff

2010-08-27 Thread Sander Sweers
On 27 August 2010 18:25, Albert-Jan Roskam  wrote:
> First, thanks for your previous replies. I cannot use IrfanView any time
> soon, nor will my boss switch to Linux.

Why not use graphicsmagick [1] which also provides a windows binary
[2]. You can execute it with the subprocess [3] module?

Greets
Sander

[1] http://www.graphicsmagick.org/convert.html
[2] ftp://ftp.graphicsmagick.org/pub/GraphicsMagick/1.3/windows/README.txt
[3] http://docs.python.org/library/subprocess.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterating over less than a full list

2010-09-04 Thread Sander Sweers
On 4 September 2010 19:14, Bill Allen  wrote:
> Say I have and iterable called some_stuff which is thousands of items in
> length and I am looping thru it as such:
>
> for x in some_stuff
>  etc...
>
> However, what if I want only to iterate through only the first ten items of
> some_stuff, for testing purposes.  Is there a concise way of specifying that
> in the for statement line?

You can use a slice or use a counter.

slice,

for x in some_stuff[:10]:
etc

counter,

count = 0

for x in some_stuff:
if x <= 10:
print x
else:
break

greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterating over less than a full list

2010-09-04 Thread Sander Sweers
On 4 September 2010 19:25, Sander Sweers  wrote:
> for x in some_stuff:
>    if x <= 10:
>        print x
>    else:
>        break

Oops, corrected version...

count = 0
for x in some_stuff:
if count < 10:
print x
count +=1
else:
break

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Sander Sweers
On 6 September 2010 19:32, Roelof Wobben  wrote:
> def index_of(val, seq, start=0):
>     """
>   >>> index_of(9, [1, 7, 11, 9, 10])
>   3
>   >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
>   3
>   >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>   6
>   >>> index_of('y', 'happy birthday')
>   4
>   >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
>   1
>   >>> index_of(5, [2, 3, 4])
>   -1
>   >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
>   -1
>     """
>     plek = 0
>     if type(seq) == type([]):
>     plek = seq.index(val)
>     elif type(seq) == type(()):
>     seq = list (seq)
>     plek = seq.index(val)
>     else :
>     plek = seq.find(val)
>     return plek

Not sure if this is correct but why don't you check for the index
attribute? It is part of both lists and strings. Also you can use
try/except to catch a ValueError. My version below, but I dislike the
list() usage...

def index_of(val, seq, start=0):
if hasattr(seq, 'index'):
try:
return seq.index(val, start)
except ValueError:
return -1
else:
try:
return list(seq).index(val, start)
except ValueError:
return -1

> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in
> __main__.index_of
>
> Failed example:
>
> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>
> Expected:
>
> 6
>
> Got:
>
> 3
>
> But in that tuple 5 is on position 3.
>
> Is the exercise here wrong ?

Looks like it, or it's a typo.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Sander Sweers
On 6 September 2010 22:28, Roelof Wobben  wrote:
> As far as I know index is not a part of tuple so I have to convert it to a
> list so I can use index.

As of version 2.6/3 a tuple does have index(). Not sure which version
you are using.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-06 Thread Sander Sweers
On 6 September 2010 21:45, Sander Sweers  wrote:
>> Is the exercise here wrong ?
>
> Looks like it, or it's a typo.

Now that I had a better look the test is correct. Now it is up to you
to figure out why your index_of() fails. Walter gave you a good hint.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slicing a string

2010-09-06 Thread Sander Sweers
On 7 September 2010 00:14, lists  wrote:
> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
>
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

How does it not "work"? What did you expect to happen? What did it do instead?

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: wierd replace problem

2010-09-14 Thread Sander Sweers

- Original message -
> Look at the backslash! It doesn't strip the backslash in the string, but 
> it escapes the double quote following it.
> 
> I don't know how people can explain it any better.

Maybe the link below makes it clear what backslash really does.

http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%e2%80%94-backslashes-are-escape-characters/

Greets
sander 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Sander Sweers
On 27 September 2010 22:00, Alex Hall  wrote:
> That makes sense. Basically, the * operator in this case acts as a
> copying command. For simple data types this is fine, but throw in a
> complex type, in this case a list (though I expect that any object
> would do this) and you are just doing what Python does to copy
> objects: copying the memory location, not making a deep copy and
> getting a duplicate object.

It does not copy the object it makes multiple _references_ to the *same* object.

So let's say you have a list [1,2,3] with variable a which is a list
object containing 3 integer objects. Following Steven´s example you
basically create a new list with 3 references to the first list with
variable a. You could just as well have written it as [a,a,a] which is
the same as [a] * 3.

>>> a = [1,2,3]
>>> b = [a,a,a]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[[10, 2, 3], [10, 2, 3], [10, 2, 3]]

The next step is how do we create a real copy of the object instead of
a new reference to the same object. There are multiple methods to
create a copy.

The easiest is using a slice. A slice returns (in this example) a
*new* list with all the values.
>>> b = [a[:],a[:],a[:]]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b[0][0] = 10
>>> b
[[10, 2, 3], [1, 2, 3], [1, 2, 3]]

Or use the copy modules to do the same, see help(copy) for more info.
>>> import copy
>>> a = [1,2,3]
>>> b = [copy.copy(a), copy.copy(a), copy.copy(a)]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b[0][0] = 10
>>> b
[[10, 2, 3], [1, 2, 3], [1, 2, 3]]

copy.copy(a) is what we call a shallow copy. It only make a copy of
the list object a. But what if list object a again contained 3 list
objects? You then run into the same problem as before.

>>> a = [[1,2],[3,4],[5,6]]
>>> b = [copy.copy(a), copy.copy(a), copy.copy(a)]
>>> b
[[[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]]]
>>> a[0][0] = 10
>>> b
[[[10, 2], [3, 4], [5, 6]], [[10, 2], [3, 4], [5, 6]], [[10, 2], [3,
4], [5, 6]]]

For this you can use copy.deepcopy() which make sure you create a copy
of each object (in this case lists).

I found this was one of the most weird things I needed to understand
about python.

Hope this helps.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Sander Sweers
On 27 September 2010 23:15, Sander Sweers  wrote:
>> objects: copying the memory location, not making a deep copy and
>> getting a duplicate object.
>
> It does not copy the object it makes multiple _references_ to the *same* 
> object.

Oops, You already got the idea and I should have read better. Ow well,
maybe the copy module was of interest to you.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] using "in" with a dictionary

2010-09-28 Thread Sander Sweers
On 28 September 2010 23:58, Alex Hall  wrote:
> Hi all, yet again:
> I have a dictionary that will look something like:
> d={
>  (1,2):"a",
>  (3,4):"b"
> }
>
> How can I say:
> if (1,2) in d: print d[(1,2)]

This will work fine.

> This is false

Not it is not..
>>> d = {(1,2):"a",(3,4):"b"}
>>> (1,2) in d
True

>, so I expect to have to use d.keys, but I am not quite sure how.
> I will be using this in a loop, and I have to know if there is a key
> in the dictionary called (i,j) and, if there is, I have to grab the
> value at that slot. If not I have to print something else.

>>> d = {1:"a",2:"b"}
>>> for x in range(1,4):
if x in d:
print "Found %s in dict d and has value %s" % (x, d[x])
else:
print "Value %s is not in dict d" % x


Found 1 in dict d and has value a
Found 2 in dict d and has value b
Value 3 is not in dict d

> When I tried "in" in the interpreter, I got something about builtin function
> not being iterable. TIA for any suggestions.

What was the code you tried out? Please do provide this as it helps
figure out what was going on.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using contents of a document to change file names, (was Re: how to extract data only after a certain ...)

2010-10-12 Thread Sander Sweers
On 12 October 2010 21:15, Joel Goldstick  wrote:
> When the dictionary is retrieved, its order depends on the hashed values
> rather than the keys themself.

If (big IF here) you really need an ordered dict you can use the
OrderedDict from the collections module. However this will only
guarantee *insertion* order (except for existing keys). Do make sure
you read pep 372 [1].

Greets
Sander

[1] http://www.python.org/dev/peps/pep-0372/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting from unicode to nonstring

2010-10-14 Thread Sander Sweers
On 14 October 2010 16:14, David Hutto  wrote:
> (u'graph1', u'Line', u'222', u'BLUE', u'1,2,3,4', u'True', u'0,5,0,10')
>
> Which is a tuple of unicode strings. From this I
> need to place portions of the tuple into other fields,
> but not as unicode strings, but literals no ''.
>
> For example if I have the following line:
>
> self.lines = self.newplot.plot([1,2,3,4])

So you want convert string u'1,2,3,4' to a list of ints [1,2,3,4]?
Then the below will work.

[int(n) for n in u'1,2,3,4'.replace(',', '')]

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting from unicode to nonstring

2010-10-14 Thread Sander Sweers
On 14 October 2010 20:29, David Hutto  wrote:
> Actually, I needed it to be converted to something without a string
> attached to it. See a post above, and it was fixed by eval(),

Using eval is a big security risk and is generally not recommended for
any production code. What do you think eval() return for your string?
A tuple of ints which for your use case serves the same purpose as
using the list comprehension.

If you really want (you really don't) to use eval() then at least use
the safe one from the ast mode.

>>> from ast import literal_eval
>>> literal_eval(u'1,2,3,4')
(1, 2, 3, 4)
>>> eval(u'1,2,3,4')
(1, 2, 3, 4)

As you can see for your use case both return a tuple of ints.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting from unicode to nonstring

2010-10-14 Thread Sander Sweers
On 14 October 2010 21:02, Sander Sweers  wrote:
> If you really want (you really don't) to use eval() then at least use

Oops, hit send to soon. "(you really don't)" should have been "(you
really don't need to use it)".

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Requesting restricted URL (further authentication requested)

2010-10-19 Thread Sander Sweers
On 19 October 2010 21:56, Tim Johnson  wrote:
> I've written the following function which successfully gets an
> authenticated URL:
> def getRestrictedURL(authName,URL,log,pswd):
>        auth_handler = urllib2.HTTPBasicAuthHandler()
>        auth_handler.add_password(authName, URL,log,pswd)
>        opener = urllib2.build_opener(auth_handler)
>        urllib2.install_opener(opener)
>        return opener.open(URL).read()

The above should be:
data = opener.open(URL).read() #does the initial authentication.
return opener #return the opener object not the data you read.

> # But, alas, any links in content 'beneath' the URL
> # require additional authentication.

You are almost there. In order to authenticate initially you indeed
need to read the page. But then what you want is to return the opener
object, not the page you read which you do currently. The opener
object holds the authentication data and this opener object you will
need to use for every new url you want to read, opener.open().

Depending on what you want to do with the data you might want to split
this up into 2 functions. One that will authenticate and another that
read the url and returns the data. The second function would need to
be passed the opener object which the first one returned.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does "TypeError: 'int' object is not iterable" mean?

2010-10-21 Thread Sander Sweers
On 21 October 2010 18:09, Richard D. Moores  wrote:
> In case anyone's interested, the script now works the way I wanted:
> . It should work for anyone
> with 2.6 or 2.7
>
> I'd appreciate constructive criticism.

Instead of all the zeros2float craziness use string formatting. It
will take care of rounding and the number of decimal places.

>>> import datetime
>>> lowz = 81.747345
>>> timestamp = datetime.datetime.now().strftime("%H:%M:%S")
>>> print "NEW LOW: %.4f at %s" % (lowz, timestamp)
NEW LOW: 81.7500 at 22:55:13

If you want to control the number of decimal places in the string
formatting do something like:

>>> i = 3
>>> print ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp)
NEW LOW: 81.750 at 22:55:13
>>> i = 6
>>> print ("NEW LOW: %%.%sf at %%s" % i) % (lowz, timestamp)
NEW LOW: 81.75 at 22:55:13

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with converting script using 2.6's urllib2 to Python 3.1

2010-10-25 Thread Sander Sweers
On 25 October 2010 14:46, Richard D. Moores  wrote:
> I'd like to convert the script to 3.1, but I can't understand the docs
> for the 3.1 urllib module. Please someone tell me what to do.
> (Converting   'print rate'   to   'print(rate)'   I understand.)

Have you actually tried reading the documentation? The _very_ first
section of the urllib documentation we have urllib.request.urlopen
[1]. Which looks to me what you are looking for as a replacement to
urllib2.urlopen().

Some *untested* inline comments below.

> import urllib2
from urllib import request
> a = 
> urllib2.urlopen('http://www.marketwatch.com/investing/currency/CUR_USDYEN').read(20500)
a = 
request.urlopen('http://www.marketwatch.com/investing/currency/CUR_USDYEN').read(20500)
> b = a[19000:20500]
> idx_pricewrap = b.find('pricewrap')
> context = b[idx_pricewrap:idx_pricewrap+80]
> idx_bgLast = context.find('bgLast')
> rate = context[idx_bgLast+8:idx_bgLast+15]
> print rate
print(rate)

Also http://docs.python.org/library/2to3.html discusses the automated
tool for converting python code.

Greets
Sander

[1] 
http://docs.python.org/py3k/library/urllib.request.html#urllib.request.urlopen
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help with converting script using 2.6's urllib2 to Python 3.1

2010-10-25 Thread Sander Sweers
On 25 October 2010 18:19, Richard D. Moores  wrote:
> Doing it your way,
>
> from urllib import request
> a = 
> request.urlopen('http://www.marketwatch.com/investing/currency/CUR_USDYEN').read(20500)
> print(a[123:140])
>
> succeeds. Why?

Not sure how this exactly works but this is what I know. The
difference is that urllib is now a directory with files in it while
urllib2 was a single file. When you import  on a a single file
module normally all functions and classes are available to you.

Now that this is a directory some magic (or not?) has to happen in
__init__.py (read I also don't know). But I am sure someone here will
be able to explain this properly :-).

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting a numerical variable into a string variable

2009-02-12 Thread Sander Sweers
On Thu, Feb 12, 2009 at 21:06, Andres Sanchez  wrote:
> Please, give me a hand with this. Say I have a vector defined as
> x=[1,2,3,4,...,9]. I need to write string variables with the names
> G1BF...G9BF. Thus, the first string variable would be 'G'+'1'+'BF', being
> the number 1 equal to x[0]. Now, using a for loop, I want to do something
> like: y[i]='G'+x[i-1]+'BF' , to create my string variables. Yes, the problem
> is that I am mixing numerical and string variables and Python reports an
> error when I try to do this. So, the question is: how do I do to convert the
> numerical variable x[0]=1 into a string variable '1', so I can do my
> 'G'+'1'+BF' thing?

>>> x = 100
>>> x
100
>>> str(x)
'100'

You can use str() to convert the numbers to strings. To print what you
are looking for do something like this.

>>> x = [x for x in range(1,10)]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> for var in x:
print 'G' + str(var) + 'BF'


G1BF
G2BF
G3BF
G4BF
G5BF
G6BF
G7BF
G8BF
G9BF

Or:

>>> for var in x:
print 'G%sBF' % var


G1BF
G2BF
G3BF
G4BF
G5BF
G6BF
G7BF
G8BF
G9BF

> By the way, 'G'+'x[0]'+'BF' reports 'Gx[0]BF'  :)

Correct, 'x[0]' is a string not the number you are looking for. See
above on how you can do this.

Greets
Sander

PS: personally I like the second one better :-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] print function in python 2.6 and 3

2009-02-12 Thread Sander Sweers
Hello,

I see more people posting answers with the new print() function only
available in python 3 and in python 2.6 via an import from __future__.
Now I am not confused by this but I can understand that people very
new to python can get confused byt this. Especially people following a
guide online or a book which almost all use the old print statement.

Now what should be used and promoted on the list?

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print function in python 2.6 and 3

2009-02-12 Thread Sander Sweers
On Thu, Feb 12, 2009 at 22:50, Alan Gauld  wrote:
>> Now what should be used and promoted on the list?
>
> We can't shouldn't promote one over the other since the remit
> of this list is to help newbies, regardless of the Python version.

OK, understood.

> The only thing I would strongly request is that posters specify
> the Python version (both in questions and replies) . That's always
> a good idea but especially during a time of change.

Maybe it is an idea to actively request the versoin if not immediatly obvious?

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib unquote

2009-02-16 Thread Sander Sweers
On Mon, Feb 16, 2009 at 14:12, Norman Khine  wrote:
> Type "help", "copyright", "credits" or "license" for more information.
 import base64, urllib
 data = 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A'
 data = urllib.unquote(data)
 print base64.decodestring(data)
> ???Ը???Nzv̊??z?+?

>
> What am I missing?

Not an expert here but I think you can skip the last step...

>>> urllib.unquote('hL/FGNS40fjoTnp2zIqq73reK60%3D%0A')
'hL/FGNS40fjoTnp2zIqq73reK60=\n'


Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib unquote

2009-02-17 Thread Sander Sweers
On Tue, Feb 17, 2009 at 08:54, Norman Khine  wrote:
> Thank you, but is it possible to get the original string from this?

You mean something like this?

>>> urllib.quote('hL/FGNS40fjoTnp2zIqq73reK60=\n')
'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting "HH:MM:SS" to datetime

2009-03-01 Thread Sander Sweers
2009/3/1 Wayne Watson :
> Ok, how do I do what's mentioned in Subject?

Googling for python and time gives as first result.

http://www.doughellmann.com/PyMOTW/datetime/index.html

Which covers all you need to know to solve this.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting "HH:MM:SS" to datetime

2009-03-01 Thread Sander Sweers
2009/3/1 Sander Sweers :
>
> Googling for python and time gives as first result.

Sorry this is not correct, ignore it.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Convert XML codes to "normal" text?

2009-03-04 Thread Sander Sweers
2009/3/4 Eric Dorsey :
> d = feedparser.parse('http://snipt.net/dorseye/feed')
>
> x=0
> for i in d['entries']:
>     print d['entries'][x].title
>     print d['entries'][x].summary
>     print
>     x+=1
>
> Output
>
> Explode / Implode List
> >>> V = list(V)



> I know, for example, that the > code means >, but what I don't know is
> how to convert it in all my data to show properly? In all the feedparser



What you are looking for is unescape from saxutils. Example:

>>> from xml.sax.saxutils import unescape
>>> unescape('>')
'>'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] could someone explain why this happens to me.

2009-03-07 Thread Sander Sweers
2009/3/7 Alan Gauld :
>> mycopy = original[:]
>
> Returns a slice of the original list. In this case it so happens
> the slice is the full list.
>
>> mycopy = list(original)
>
> Use the list type constructor to make a list out of its argument.
> It just so happens the argument in this case is a list.

Both not give the desired result with nested lists and this is why you have..

>> mycopy = copy.deepcopy(original)
>
> calls the deepcopy function which traverses the original list
> and all nested structures explicitly copying the elements.

copy.deepcopy :-)

>>> import copy
>>> list1 = [1,2]
>>> list2 = [3.4]
>>> list3 = [list1, list2]
>>> list4 = list(list3)
>>> list5 = list3[:]
>>> list6 = copy.deepcopy(list3)
>>> list1.append('a')
>>> list1
[1, 2, 'a']
>>> list3
[[1, 2, 'a'], [3.3999]]
>>> list4
[[1, 2, 'a'], [3.3999]]
>>> list5
[[1, 2, 'a'], [3.3999]]
>>> list6
[[1, 2], [3.3999]]

Notice that list6 is the only list which does not have the appended a.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating new dictionary based on membership testing

2009-03-09 Thread Sander Sweers
2009/3/9 A.T.Hofkamp :
> You can do something like
> [d for d in d1 if d['is_selected'] == False]
> to get your dicts.
>
> If 'is_selected' is not always present, it gets a bit more complicated, I'll
> leave that as an exercise for the interested reader :)

You would use d.get('is_selected', False) == False.

If nothing is found then .get() will return False instead of None.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] memory error files over 100MB

2009-03-10 Thread Sander Sweers
2009/3/10 Alan Gauld :
>>           newFile.write(zf.read(zfilename))
>
> Remember you are reading the file into memory and then writing it
> out again in a single operation, that will use twice the space of the
> uncompressed files - plus some extra for overhead.

Question, Do you mean the file in the zipfile (zfilename) or the whole
zipfile (zf)? I would expect zf.read(zfilename) to only read the
requested file in the zipfile.

Thanks
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] incrementing one minute

2009-03-30 Thread Sander Sweers
2009/3/30 pa yo :
> I need to add one minute to a string that has a date and a time in
> MMDDHHMM format.
> e.g:  200903281346 should become 200903281347
>
> the following script converts the string into time and adds one
> minute; but somehow I also add an hour and I don't understand why.
>
> 
>
> import time
>
> #set the initial time as a string and convert it into time format:
> fromtimestring = '200903281346'
> fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M")
> #convert this time format into UNIX time (seconds since the start of UNIX 
> time):
> fromtimeseconds = time.mktime(fromtimetime)
> #add 60 seconds and reformat the result into the MMDDHHMM format
> totimeseconds = fromtimeseconds + 60
> totimetime = time.gmtime(totimeseconds)
> # convert the new time into a string:
> totimestring = time.strftime("%Y%m%d%H%M", totimetime)
>
> #print the results:
> print (fromtimestring)
> print (fromtimetime)
> print (totimetime)
> print (totimestring)
>
> 
>
> any help or suggestions would be much appreciated.

You could do this with datetime and timedelta from the datetime module.

>>> from datetime import datetime, timedelta
>>> fromtimetime = datetime.strptime('200903281346', '%Y%m%d%H%M')
>>> fromtimetime
datetime.datetime(2009, 3, 28, 13, 46)
>>> delta = timedelta(seconds=60)
>>> delta
datetime.timedelta(0, 60)
>>> fromtimetime + delta
datetime.datetime(2009, 3, 28, 13, 47)
>>> datetime.strftime(fromtimetime + delta, '%Y%m%d%H%M')
'200903281347'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.popen3 > subprocess.Popen but nohup.out won't go

2009-04-04 Thread Sander Sweers
2009/4/4 dave selby :
> os.popen3('nohup %s/core/kmotion_hkd2.py &> /dev/null &' % kmotion_dir)
>
> becomes ..
>
> subprocess.Popen('nohup %s/core/kmotion_hkd2.py &> /dev/null &' %
> kmotion_dir, shell=True)
>
> all is well except I now get
>
> nohup: appending output to `nohup.out'
>
> on the terminal which '&> /dev/null' used to ditch to /dev/null. I
> think this is because subprocess simulates the
> shell differently. Any idea how to ditch to /dev/null in subprocess ?

Subprocess by default does not store stdout and stderror. Try this:

proc = subprocess.Popen('nohup %s/core/kmotion_hkd2.py' % kmotion_dir,
shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)

Now proc.communicate returns a tuple with (stdout, strderr). You can
also make stdout/stderr go to a file, below untested!

outfile = open('/tmp/myoutfile')
errfile = open('/tmp/myerrfile')

proc = subprocess.Popen('nohup %s/core/kmotion_hkd2.py' % kmotion_dir,
shell=True, stdout=outfile,stderr=errfile)

proc.communicate()

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.popen3 > subprocess.Popen but nohup.out won't go

2009-04-04 Thread Sander Sweers
2009/4/4 Sander Sweers :

Bah, of course you need to open the files writable :-(

This

> outfile = open('/tmp/myoutfile')
> errfile = open('/tmp/myerrfile')

Should be

outfile = open('/tmp/myoutfile', 'w')
errfile =open('/tmp/myerrfile', 'w')

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Append a dictionary value

2009-04-04 Thread Sander Sweers
2009/4/4 David :
> I put together a todo program here;
> http://linuxcrazy.pastebin.com/f74beaf78
>
> And I am trying to add an option to edit the values which are date and time.
> Below I have gotten this far but now I need some help. looks like my attempt
> to use setdefault will not work. Please point me in the right direction my
> head has started to hurt :)

I do not understand what it is you want to do. Do you want to replace
the old date and time with the new? If so you already do this with
todo[answer] = datevalue, time. Why do you want to use setdefault?

> #!/usr/bin/python
> import time
> import datetime
> todo = {'Study Python':
>        (datetime.date(2009, 4, 1), datetime.time(12, 15)),
>        'Clean House':
>        (datetime.date(2009, 4, 4), datetime.time(15, 15)),
>        'Fix Python Code':
>        (datetime.date(2009, 3, 29), datetime.time(9, 1))}

Why not use a datetime object?

todo = {'Study Python':
(datetime.datetime(2009, 4, 1,12,15)}

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please use plain text.

2009-04-07 Thread Sander Sweers
2009/4/7 Wayne Watson :
> What I would consider a big difficulty with flat text is exactly that it is
> flat. There are lots of times, in my experience, when a graphic,
> particularly captured ones, can lead to much faster and smarter solution. I
> think this list may allow them, but it seems at a delay.

The problem lies not with plain text but how people write text. If one
structures their e-mails properly it does not make any difference if
it is in plain text or rtf/html.

rtf/html also do not guarantee that your indentation is displayed
properly. So if one want to keep using html/rtf I would recommend
using a pastebin.

> My experience is
> the opposite of yours with forums. I use Yahoo Groups fairly often. Although
> I don't like the advertising present there, which is pretty minimal, they at
> least something of a cross between graphics and text. One can upload images
> for examination by others. Some forums and all YGs even allow videos. I've
> even used videos to solve some hardware problems.

If you need to show your code with proper indentation and syntax
highligthing use a pastebin. Also there are many places where one can
upload (for free) pictures and videos which then can be linked to in
the message.

> Maybe mail lists should be
> divided into segments. Say, one for people who use text and others for
> whatever media they are comfortable with.

And this accomplishes that tutors will have to read multiple lists and
keep track of which list they are tutoring. If I was one of them I
would refuse. It also does not solve the problem highlighted earlier.

So I agree with Bob that on *mailing lists* plain text is the
preferred format. But other formats should not be _rejected_ as this
would scare away potential pythoniasts which goes against the gaol of
the mailing list.

Anyhow, this discussion has gone way off topic and I suggest all to
drop it as it will only lead to flame wars.

Greets
Sander

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing in e-mail?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ideas on how to process a file

2009-04-10 Thread Sander Sweers
2009/4/10 Spencer Parker :
> The question is now...what do I do to find duplicate entries in the text
> file I am reading.  I just want to filter them out.  There are a ton of
> duplicate entries in there.



>>> for line in text_file: # No need for readlines(), a file is iterable
>>>  if 'FULLNAME' in line:
>>>    write_file.write(line)  # writelines() is for writing multiple lines
>>> at once

results = []

for line in text_file:
if 'FULLNAME' in line and line not in results:
results.append(line)
write_file.write(line)

Now you write out line immeditaly or wait and write out the results list.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Make beautifulsoup show the data it has an issue with

2009-04-10 Thread Sander Sweers
Hello Tutors,

I am having some issues with a malformed tag in a html page.
BeautifulSoup barfs with the following.

raceback (most recent call last):
  File "", line 1, in 
tsoup = BeautifulSoup(readPage('http://url.sanitized'))
  File "C:\Python25\lib\site-packages\BeautifulSoup.py", line 1493, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
  File "C:\Python25\lib\site-packages\BeautifulSoup.py", line 1224, in __init__
self._feed(isHTML=isHTML)
  File "C:\Python25\lib\site-packages\BeautifulSoup.py", line 1257, in _feed
self.builder.feed(markup)
  File "C:\Python25\lib\HTMLParser.py", line 108, in feed
self.goahead(0)
  File "C:\Python25\lib\HTMLParser.py", line 148, in goahead
k = self.parse_starttag(i)
  File "C:\Python25\lib\HTMLParser.py", line 226, in parse_starttag
endpos = self.check_for_whole_start_tag(i)
  File "C:\Python25\lib\HTMLParser.py", line 301, in check_for_whole_start_tag
self.error("malformed start tag")
  File "C:\Python25\lib\HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParseError: malformed start tag, at line 167, column 73

How can I make it return the data it has an issue with?

Thanks
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to programmatically EDIT a python file using an editorof my choice ?

2009-04-12 Thread Sander Sweers
2009/4/12 Dominique :
> I tried several other ways without any success:
> subprocess.Popen(args = ["notepad++.exe", filename])
> subprocess.Popen(args = ["C:\Program Files\Notepad++\notepad++.exe", 
> filename])

Try this:

subprocess.Popen(args = [r'C:\Program Files\Notepad++\notepad++.exe', filename])

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Make beautifulsoup show the data it has an issue with

2009-04-12 Thread Sander Sweers
2009/4/10 Kent Johnson :
> Or, catch
> the exception, have the code find out where the error is and display
> the bad line.

This is what I was looking for. I know how to catch the exception but
how do I make it display the bad line?

Thanks
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to programmatically EDIT a python file using an editorof my choice ?

2009-04-12 Thread Sander Sweers
2009/4/12 Dominique :
> With r before the path of the software, it works perfectly.
> subprocess.Popen([r"C:\Program Files\Editra\Editra.exe", filename])
> I saw that once but I don't remember and cannot find the reason for the use 
> of r.

The r means the string is a raw string.

> I'll try not to forget to test with and without r in case a file access 
> doesn't
> work.

The real issue is what Alan pointed out. The backlash is an escape
character and if you want to use it in a string should be escaped by a
backlash.Using a raw string will give the same result as 'C:\\Program
Files\\Editra\\Editra.exe'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Make beautifulsoup show the data it has an issue with

2009-04-12 Thread Sander Sweers
2009/4/12 Kent Johnson :
> try:
>  tsoup = BeautifulSoup(data)
> except HTMLParseError, ex:

Aah, ex is the object/class which has the error data. This was the
missing piece for me.

Many thanks Kent!

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to programmatically EDIT a python file using an editorof my choice ?

2009-04-13 Thread Sander Sweers
2009/4/13 Dominique :
> What surprises me is that before calling the subprocess.Popen() method, I
> normalized the path using:
> filename = os.path.normpath(filename).

It does.But do you also call os.path.normpath for the program path?
See below an example.

>>> import os
>>> path = 'C:\Program Files\Notepad++\notepad++.exe'
>>> os.path.normpath(path)
'C:\\Program Files\\Notepad++\notepad++.exe'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with a simple logger with RotatingFileHandler

2009-04-14 Thread Sander Sweers
2009/4/14 Daniel :
> def get_logger(log_filename):
>     my_logger = logging.getLogger("MyLogger")
>     my_logger.setLevel(logging.debug)
   ^^^
You have a small typo. This should be in capitals, logging.DEBUG.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code publishing

2009-04-16 Thread Sander Sweers
2009/4/16 spir :
> I have no clue whether there is a common place to publish some (free like the 
> air) python source code for review, use, evolution...
> (It's about 17 5kb.)

Maybe http://python.pastebin.com is what you are looking for?

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is it syntactic,semantic or runtime?

2009-04-25 Thread Sander Sweers
2009/4/25 prasad rao :

> So opening blank Explorer after complaining th html file not found.
> Where is the problem?

There are typing errors on the below...

> 
> def pp():
> @@@ import urllib
> @@@ import subprocess
> @@@ so=urllib.urlopen('http://www.asstr.org')
> @@@ data=so.read()
> @@@ de=open('C:pp.html','w')

This create a file pp.html in the directory where the script was run
from. I expect you want it in c:\ so it should look like. Notice the
backslash is escaped with a backslash!

  de = open('c:\\pp.html', 'w')

> @@@ de.write(data)
> @@@ subprocess.Popen(['C:\Program Files\Internet
> xplorer\\IEXPLORE','C:pp.html'])

Again the same issue as above plus the path to iexplore.exe is bad.

  subprocess.Popen(['C:\\Program Files\\Internet
Explorer\\iexplore.exe','C:\\pp.html'])

This works for me.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to run a .py file or load a module?

2009-04-26 Thread Sander Sweers
2009/4/26 Dayo Adewunmi :
> I'm looking at recursion in "Think Python", and this is the bit of code:
>
> #!/usr/bin/env python
>
> def countdown(n):
>       if n <= 0:
>               print 'Blastoff!'
>       else:                 print n
>               countdown(n-1)
>
>
> I've typed that in vim and saved as countdown.py, but I'm not sure how to
> run it.
>
> However with this particular function that requires an argument, I'm not
> sure how to run it.
>
> I've had to type it out in the python prompt and then
> call
> the function with an argument. That works, naturally.
>
> I've also tried this:
>
>       >>>import countdown
>       >>>countdown(10)

When you import it lile this the function countdown is part of the
module countdown. So you call it like countdown.countdown(10). Or
import it like "from countdown import countdown" and then your example
will work.

> but this is the error I get:
>
>       Traceback (most recent call last):
>         File "", line 1, in 
>       NameError: name 'countdown' is not defined
>
> How can I
>
> a) Open my shell, and do something like: $ python countdown.py   but have it
> take an argument and pass it to the function, and execute.

Look at sys.argv which returns a list with the first value being the
script name and the second are the command line argument(s).
http://docs.python.org/library/sys.html

> b) Import the function in the interactive interpreter, and call it like so:
>
>       countdown(10)
>
> without getting the abovementioned error.

See above.

The script would then look like:

#!/usr/bin/env python

import sys

times = int(sys.argv[1]) # The argument given on the command line

def countdown(n):
if n <=0:
print 'Blast off!'
else:
countdown(n-1)

countdown(times)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Add newline's, wrap, a long string

2009-04-29 Thread Sander Sweers
2009/4/29 David :
> Here is the whole program so far, what it does is it logs into a druple web
> site and posts. I would like to make it better, as you can see I do the same
> thing over and over.
>
> http://linuxcrazy.pastebin.com/m7689c088

What you can do is define all the variables upfront. This way you can
get rid of the else. Below is an example how you can do this with only
looping once over the fle.

CBUILD = ''
ACCEPT_KEYWORDS = ''

for line in fname:
if 'ACCEPT_KEYWORDS' in line:
output = line.split('"')[1]
ACCEPT_KEYWORDS = textwrap.fill(output, 80)

if 'CBUILD' in line:
output = line.split('"')[1]
CBUILD = textwrap.fill(output, 80)

etc etc

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encode problem

2009-05-04 Thread Sander Sweers
2009/5/4 Kent Johnson :
> str.decode() converts a string to a unicode object. unicode.encode()
> converts a unicode object to a (byte) string. Both of these functions
> take the encoding as a parameter. When Python is given a string, but
> it needs a unicode object, or vice-versa, it will encode or decode as
> needed. The encode or decode will use the system default encoding,
> which as you have discovered is ascii. If the data being encoded or
> decoded contains non-ascii characters, you get an error that you are
> familiar with. These errors indicate that you are not correctly
> handling encoded data.

Very interesting read Kent!

So if I get it correctly you are saying the join() is joining strings
of str and unicode type? Then would it help to add a couple of "print
type(the_string), the_string" before the .join() help finding which
string is not unicode or is unicode where it shouldn't?

Thanks
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Optparse question: if only certain values are acceptable

2009-05-08 Thread Sander Sweers
2009/5/9 Terry Carroll :
> In otherwords, if the user enters:
>
>  progname -f X
>
> It runs, producing its output in format X.  Similar if "Y" or "Z" is
> specified instead of "X".
>
> But if the user specifies
>
>  progname -f A
>
> I want it to spit up because A is not a recognized format.

Is the below what you are looking for?

>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option('-f', '--format', type='choice', action='store', 
>>> choices=('x','y','z'), dest='format')
>>> args = ['-f', 'd'] #Wrong format d
>>> options, restargs = parser.parse_args(args)
Usage:  [options]

: error: option -f: invalid choice: 'd' (choose from 'x', 'y', 'z')

Traceback (most recent call last):
  File "", line 1, in 
parser.parse_args(args)
  File "C:\Python26\lib\optparse.py", line 1382, in parse_args
self.error(str(err))
  File "C:\Python26\lib\optparse.py", line 1564, in error
self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
  File "C:\Python26\lib\optparse.py", line 1554, in exit
sys.exit(status)
SystemExit: 2

>>> args = ['-f', 'x'] #Correct format x
>>> options, restargs = parser.parse_args(args)
>>> options.format
'x'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-14 Thread Sander Sweers
Forwarding to list because of mail delivery error...

2009/5/15 Sander Sweers :
> 2009/5/14 MK :
>> i am using this code to send an "cat > ThisIsMyUrl" with popen.
>
> First, I am not sure if you understand what "cat > ThisIsMyUrl"
> actually does... It waits for data on *stdin* and pipes it to
> ThisIsMyUrl. It does not provide any data to read! What is it that you
> want to accomplish?
>
> Anyway, why use cat and not use open() and write the data into it?
>  file = open(working_dir + "/" + subdir + "www.thisismyurl.com", "w")
>  file.write(your_data_string)
>  file.close()
>
>> Of cos cat now waits for the CTRL+D command.
>
> Well yes and no, cat is waiting for data on stdin and you do not seem
> to give any data to it.
>
>> How can i send this command ?
>
> CTR-D/EOF normally comes from the data you are piping into cat. For
> example the below, it pipes the string "test" to the stdin from cat
> which then redirects to a file test.txt.
>  echo "test" | cat > test.txt
>
>> def console_command(cmd):
>>        print cmd
>>        console = os.popen(cmd,"r")
>>        output = console.read()
>>        console.close()
>>        return output
>>
>> command="cat > " + working_dir + "/" + subdir + "www.thisismyurl.com"
>> console_command(command)
>
> You should really look at the subprocess module [1].
>
> Greets
> Sander
>
> [1] http://docs.python.org/library/subprocess.html
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python popen command using cat > textfile .... how to terminate

2009-05-15 Thread Sander Sweers
2009/5/15 MK :
> Ok. I explain it once more. Its not about reading the console output of
> the command. Its that i want to put a empty file in my subdirectories
> so that the name of the file is a message or url or something else.
> And if you want an empty file you can do that with
> "cat > IAmAnEmptyFileWithOnlyAName"
> under linux on the CLI.

Ah yes, cat is not what you will wan to use. You can use the unix
touch command or use python's open().

Example touch and subproces (untested!).

---
import subprocess
command = subprocess.Popen(['touch',
'/your_filepath/filename'],stdout=subprocess.PIPE)
stdout, stderr = command.communicate()
---

Example open().

---
filename = open('/your_filepath/filename', 'w')
filename.close()
---

> But the problem or advantage of is that you can put some lines in
> the text file if you want. And if youre ready youm must
> terminate the console/terminal with CTRL+D so that cat knows
> that the input is finished.

Like I said above, cat is not the right tool for this. When you use
python's open() you could also write data in the file if needed.

> Actually a very simple way i thought. But maybe not.

It is but only with the right tools ;-)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] clean text

2009-05-19 Thread Sander Sweers
2009/5/19 spir :
> def _cleanRepr(text):
>        ''' text with control chars replaced by repr() equivalent '''
>        result = ""
>        for char in text:
>                n = ord(char)
>                if (n < 32) or (n > 126 and n < 160):
>                        char = repr(char)[1:-1]
>                result += char
>        return result

Is this faster? It replaces all occurrences of each control character
in ctrlcmap for the whole string you pass to it.

ctrlcmap = dict((chr(x), repr(chr(x))[1:-1]) for x in range(160) if x
< 32 or x > 126 and x < 160)
teststring = chr(127) + 'mytestring'

def _cleanRepr(text, ctrlcmap):
for ctrlc in ctrlcmap.keys():
 text = text.replace(ctrlc, ctrlcmap[ctrlc])
return text

>>> teststring
'\x7fmytestring'

>>> _cleanRepr(teststring, ctrlcmap)
'\\x7fmytestring'

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can't print a string, gives me syntax error

2009-05-25 Thread Sander Sweers
2009/5/25 xbmuncher :
> I ran this in IDLE:
 t = 'hi'
 print t
> SyntaxError: invalid syntax (, line 1)

What version of python are you using (I suspect version 3)?

> I've also tried this as sample.py :
> import string
> text = 'hello world'
> print text

If you are using python 3 then the print statement has been replaced
by the print function. Try:

print(text)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CVS File Opening

2009-05-26 Thread Sander Sweers
2009/5/26 Paras K. :
> Hello,
>
> I have been working on this script / program all weekend. I emailed this
> address before and got some great help. I hope that I can get that again!
>
>
> First to explain what I need to do:
>
> Have about 6 CSV files that I need to read. Then I need to split based on a
> range of IP address and if the count number is larger than 75.
>
> I currently merge all the CSV files by using the command line:
>
> C:Reports> copy *.csv merge.csv
>
> Then I run the dos command: for /F "TOKENS=* SKIP=1" %i in ('find "."
> merge.csv ^| find /v ""') do echo %i>> P2PMerge.csv
>
> From some of my friends they tell me that should remove that last carriage
> return, which it does, however when it goes through the python script it
> returns no values.

Why would you need to strip off a carriage return? And why would you
not process the csv files one after another? It would be easier to
have some example data.

> Now if I open the merge.csv and remove that carriage return manually and
> save it as P2PMerge.csv the script runs just fine.
>
> Here is my source code:
>
> # P2P Report / Bitorrent Report
> # Version 1.0
> # Last Updated: May 26, 2009
> # This script is designed to go through the cvs files and find the valid IP
> Address
> # Then copys them all to a new file
> import sys
> import win32api
> import win32ui
> import shutil
> import string
> import os
> import os.path
> import csv

You import csv but do not use it below?

> #Global Variables
> P2Pfiles = []
> totalcount = 0
> t = 0
> #still in the development process -- where to get the files from
> #right now the location is C:\P2P
> def getp2preportdestion():
>     win32ui.MessageBox('Welcome to P2P Reporting.\nThis program is designed
> to aid in the P2P reporting. \n\nThe locations of P2P Reports should be in
> C:\P2P \nWith no subdirectories.\n\nVersion 1.0 - \n\nPress "OK" to continue
> with this program.')
>     p2preport = 'C://P2P\\'
>     return p2preport
>
>
> #Main Program
> #Get location of directories
> p2ploc = getp2preportdestion()
> #Checking to make sure directory is there.
> if os.path.exists(p2ploc):
>     if os.path.isfile(p2ploc +'/p2pmerge.csv'):
>     win32ui.MessageBox('P2PMerge.csv file does exists.\n\nWill continue
> with P2P Reporting.')
>     else:
>  win32ui.MessageBox('P2PMerge.csv files does not exists. \n\nPlease
> run XXX.bat files first.')
>  sys.exit()
> else:
>     win32ui.MessageBox('The C:\P2P directory does not exists.\n\nPlease
> create and copy all the files there.\nThen re-run this script')
>     sys.exit()
> fh = open('C://P2P/P2PMerge.csv', "rb")
> ff = open('C://P2P/P2PComplete.csv', "wb")
> igot1 = fh.readlines()
>
> for line in igot1:

You can also write the below and get rid of igot1.
for line in fh.readlines():

>     readline = line
>     ipline = readline
>     ctline = readline

You are making variables to the same object and all are not necessary.
See below idle session which should show what I mean.

>>> line = [1,2,3,4]
>>> readline = line
>>> ipline = readline
>>> ctline = readline
>>> line
[1, 2, 3, 4]
>>> line.append('This will be copied to readline, iplin and ctline')
>>> readline
[1, 2, 3, 4, 'This will be copied to readline, iplin and ctline']
>>> ipline
[1, 2, 3, 4, 'This will be copied to readline, iplin and ctline']
>>> ctline
[1, 2, 3, 4, 'This will be copied to readline, iplin and ctline']

>     count = ctline.split(',')[2]
>     count2 = int(count)
>     print count2
>     t = count2

Again making variables to the same object? And you really do not not need t.

>     ip = ipline.split(' ')[0]

so all the above can be simplified like:
   data = line.split(' ')
   count = int(data[2])
   ip = data[0]

>     split_ip = ip.split('.')
>     if ((split_ip[0] == '192') and (t >=75)):

The above then would be:
   if ip.startswith('192') and count >= 75:

>     ff.write(readline)
This will change as well:
   ff.write(line)

You can figure out the rest ;-)

>     totalcount +=1
>     elif ((split_ip[0] == '151') and (t >=75)):
>     ff.write(readline)
>     totalcount +=1
>     elif (((split_ip[0] == '142') and (split_ip[1]) == '152') and (t >=75)):
>   ff.write(readline)
>   totalcount +=1
>
> tc = str(totalcount)
> win32ui.MessageBox('Total Number of IPs in P2P Reporting: '+ tc)
> fh.close()
> ff.close()
>
>
> What I am looking for is an working example of how to go through the
> directory and read each csv file within that directory or how to remove the
> carriage return at the end of the csv file.

You can avoid the removal of this carriage return, read below. But if
you really need to you can use str.rstrip('carriage return').

> NOTE: This is not for a class - it is for work to assist me in reading
> multiple csv files within a couple days.
>
> Any assistance is greatly appreciated.

Use te glob module which can easilly find all csv files in a
directory. In general I would loop over each f

Re: [Tutor] Displaying range in 3.0.1

2009-05-28 Thread Sander Sweers
2009/5/28 Gregory Morton :
> I've been reading this Python 3.0.1
> tutorial(http://docs.python.org/3.0/tutorial/controlflow.html), and now I'm
> stuck at the second example in 4.3. This is what the example says the output
> should look like:

No it doen't but I can understand the confusion. More info below.

> range(5, 10)
>5 through 9
>
> range(0, 10, 3)
>0, 3, 6, 9
>
> range(-10, -100, -30)
>   -10, -40, -70
>
> But what I receive instead is the same as what I input (i.e. range(5,
> 10) just returns range(5, 10)).

What it returns is an *iterable* range object. Meaning you need to
iterate over it to get the values like in the first example.

for n in range(5,10):
print(n)

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] converting xls to csv

2009-06-06 Thread Sander Sweers
2009/6/6 Emile van Sebille :
>> for f in files:
>>    print f
>>    csv.reader(open (f), delimiter=' ', quotechar='|')
>
> you open it here, but don't save a reference to the opened file.  Try...
>      ff = csv.reader(open (f), delimiter=' ', quotechar='|')



>    reader(...)
>        csv_reader = reader(iterable [, dialect='excel']
>                                [optional keyword args])
>            for row in csv_reader:
>                process(row)

If you are on windows you should open the file in binary mode.
  open(f, 'rb')

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] converting xls to csv

2009-06-06 Thread Sander Sweers
2009/6/6 Nick Burgess :
> Is it posible to take
> the regex compile from user input?  To make it take an argument,  like
>
>> csvSearch.py 10.192.55

You can use raw_inpout() see [1] for the docs
  user_input = raw_input('Please provide input')

Greets
Sander

[1] http://docs.python.org/library/functions.html#raw_input
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] converting xls to csv

2009-06-07 Thread Sander Sweers
On Sun, 2009-06-07 at 00:54 +0200, Sander Sweers wrote:
> 2009/6/6 Nick Burgess :
> > Is it posible to take
> > the regex compile from user input?  To make it take an argument,  like
> >
> >> csvSearch.py 10.192.55
> 
> You can use raw_input() see [1] for the docs
>   user_input = raw_input('Please provide input')

Ugh, I really should not write e-mail 2 in the morning :(

What you are looking for is command line options. Command line options
are stored in sys.argv, see [1].

import sys
opts = sys.argv[1:] #sys.argv[0] is filename
print opts

You will need to validate the input so your module does not raise an
exception.

If you are planning to do more advanced commandline options you should
look at the optparse module [2].

Greets
Sander

[1] http://docs.python.org/library/sys.html#sys.argv
[2] http://docs.python.org/library/optparse.html

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   3   >