[Tutor] Documenting a Module

2010-09-13 Thread Michael Powe
Hello,

Are there any tools for documenting a module other than Sphinx? 

Apparently, I need a full-blown dev box with Visual Studio installed
to get Sphinx up, due to the dependency on Jinja, which comes
source-only and requires VC. 

I wrote a module, I'd like to produce a decent document of its
functionality from the comments and doc strings; and I already wasted
a considerable part of my Sunday afternoon trying to get along with
Sphinx. I'm not talking about a huge Python project, nor am I likely
to need that type of documentation tool in the near future.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA


Is it time for your medication or mine?


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


Re: [Tutor] Documenting a Module

2010-09-13 Thread r...@schoenian-online.de

Hi Michael,
 
I can recommend epydoc. You can find it here:
 http://epydoc.sourceforge.net/ It's a nice tool and you should have no problems
with the installation.
 
Ralf
 
 
 

Michael Powe  hat am 13. September 2010 um 11:54
geschrieben:

> Hello,
>
> Are there any tools for documenting a module other than Sphinx?
>
> Apparently, I need a full-blown dev box with Visual Studio installed
> to get Sphinx up, due to the dependency on Jinja, which comes
> source-only and requires VC.
>
> I wrote a module, I'd like to produce a decent document of its
> functionality from the comments and doc strings; and I already wasted
> a considerable part of my Sunday afternoon trying to get along with
> Sphinx. I'm not talking about a huge Python project, nor am I likely
> to need that type of documentation tool in the near future.
>
> Thanks.
>
> mp
>
> --
> Michael Powe                mich...@trollope.org                Naugatuck CT
> USA
>
>
> Is it time for your medication or mine?___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exceptions problem

2010-09-13 Thread Francesco Loffredo

On 11/09/2010 20.43, bob gailer wrote:

On 9/11/2010 12:12 PM, Roelof Wobben wrote:

...

You can't.

I made that comment in the context of the OPs function:

def readposint():
x = raw_input("Please enter a positive integer :")
try:
if (int(x)<0 or (float(x) - int(x)> 0)): raise(ValueError)
except:
print x , "is not a positive integer. Try again."
return -1
return x

The OP thought (incorrectly) that, given for example:
x = '3.1'
float(x) - int(x) would evaluate to 0.1

In reality int(x) in this case raises an exception.
ValueError: invalid literal for int() with base 10: '3.1'

Since the expression was in a try he could not tell exactly what was
happening.

I also don't quite understand the use of raise in the try.
It took me some time to understand that OP was... me! What do you mean 
by OP? If it stands (as usual) for Original Poster, he (Roelof Wobben) 
did not write this piece of cleverly crafted code. It was me, and I'm 
glad to show you its internals.
My aim was to exclude everything but positive integers, and so I did by 
EAFP programming. You pointed out that int('3.1') throws an exception, 
as I did not know.

*So what?*
My little readposint() function only needed to let POSITIVE INTEGERS go, 
and so it does. Everything else generates an exception, even positive 
floats (thanks to the raise inserted in a try), and I handle it 
informing the user and returning a well-defined and repeatable wrong 
value, that can be easily handled.
Sure, I could make the funcion more efficient, and nearly all of you can 
make it more Pythonic, whatever that means. But I thought it was quite 
sufficient, for a school exercise.
Note that int('7') returns, correctly, 7, while float('5.2') returns 5.2 
as expected. I don't like this rough behaviour of int(), spitting out an 
exception if given a legitimate string representation of a float. Can 
some of you Tutors explain me why it must be so?



I wish and hope that Roelof will learn how to do program walkthroughs
and use the interactive prompt to solve things himself. I applaud the
patience some of you have ih hand-holding him. I don't have that
patience. I wish him to learn to fish.
I don't like fishing, but many fishermen friends of mine tell me it's 
something that greatly improve patience. If you lack this quality, as 
you said, then you're the one who should go fishing...



Hello Bob,

Oke, I try to fish.


Thank you.
I hope you will keep trying to learn programming and Python too, Roelof. 
You show tenacity and determination, and those (with patience, I would 
add) are very useful in serious programming. Anyway, remember the Python 
shell is your friend, make good use of it!




Are these the right conclusions ??

Roelof
You're very close, Roelof. I just wanted to produce exactly the same 
error message and result for any wrong value inserted, and return the 
right number if the right number was input by the user. So I started 
with (int(x) < 0) to get rid of all that int() cannot handle (I never 
knew it couldn't handle "3.2", but for now it's OK) and also negative 
integers (and negative floats, I thought); then I found a way to exclude 
positive floats. I think this is what(float(x) - int(x) > 0) can do. I 
pseudo code, my function is:


input value
if (value is not a positive integer): throw exception
else: return value.
exception: inform user
   return -1.

Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3130 -  Data di rilascio: 
09/12/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] classmethod, staticmethod functions (decorator related)

2010-09-13 Thread Steven D'Aprano
On Mon, 13 Sep 2010 12:29:07 pm Huy Ton That wrote:
> Hm, thanks guys; I just had to verify I was thinking sanely about it.
> I am going to pick up classmethods next. Do any of you have common
> design patterns for the usage. They are just items I haven't
> integrated in my coding, and I want to be certain I'm off on the
> right foot (:

The most common use for classmethods is to implement alternative 
constructors. For example, in the Decimal class starting in version 2.7 
and 3.1, you have two constructors:

>>> from decimal import Decimal
>>> Decimal("1.2345")
Decimal('1.2345')
>>> Decimal.from_float(1.2345)
Decimal('1.2344307220832633902318775653839111328125')

from_float is a class method.


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


Re: [Tutor] exceptions problem

2010-09-13 Thread Steven D'Aprano
On Mon, 13 Sep 2010 08:55:46 pm Francesco Loffredo wrote:
> I don't like this rough behaviour of int(), spitting out an
> exception if given a legitimate string representation of a float. Can
> some of you Tutors explain me why it must be so?

The int() function behaves as a constructor, producing an integer object 
from its argument. It has two jobs:

(1) truncate (round-to-zero) numbers to a whole number by dropping any 
fraction part without rounding; and

(2) convert strings to an integer.


So int() can truncate all of these numbers:

>>> from decimal import Decimal
>>> from fractions import Fraction
>>> int(3)  # an int is already an int, so no change
3
>>> int(5.6)
5
>>> int(Decimal("-1.2"))
-1
>>> int(Fraction(12, 5))
2


But not this one, because it's not clear what the integer part of a 
complex number is:

>>> int(5.23 + 11.76j)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can't convert complex to int


Okay, that's numbers out of the way. Pretty straightforward.

When it comes to strings, we're doing *conversions*, not truncation, so 
we need to decide what are the rules for converting strings. The usual 
rule is that, apart from a possible leading + or - sign, we expect a 
string of digits. Nobody expects int("two hundred and thirty-seven") to 
return 237. What digits are allowed? That depends on the base -- Python 
supports bases from 2 to 36:

>>> int("123")  # base 10 is the default
123
>>> int("123ff", 16)  # hexadecimal
74751
>>> int("123ff", 36)
1777371

There's also a "base 0", which uses the string's prefix to specify the 
base:

>>> int("0x123ff", 0)  # 0x... means a hex number
74751


So what are we to make of a string like "1.95"? Obviously it's not an 
integer, and "." is not a valid digit. If you, the programmer, are 
reading in data from a file and are expecting *integers*, and somebody 
slipped in a decimal-point, that is just as troublesome as if they 
slipped in a semi-colon or the letter Z. Should "1.95" be truncated to 
1, or rounded to 2? Should it remain a float? Should the dot be 
interpreted as a digit in some unusual base?

Python refuses to guess what int("1.95") should mean, and it raises an 
error, just as it does for int("1+1") or int("two").


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


[Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben

Hello, 

I have this string called test with the contents of 'het is een wonder \\TIS'

Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
And I get at the python prompt this answer : 'het is een wonder TIS' 
So that's right.

Now I try the same in a IDE with this programm :
 
woorden =[]
letter_counts = {}
file = open ('alice_in_wonderland.txt', 'r')
for line in file:
line2 = line.replace ("\\","")
line3 = line2.lower()
woorden = line3.split()
for letter in woorden:
letter_counts[letter] = letter_counts.get (letter, 0) + 1
letter_items = letter_counts.items()
letter_items.sort()
print letter_items 
 
But now Im gettting this output :
 
[('"\'tis', 1), 
 
Why does the \ stays here. It should have gone as the test in the python prompt 
says.
 
Roelof


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


Re: [Tutor] exceptions problem

2010-09-13 Thread Francesco Loffredo

First, *THANK YOU!* for your clear and thorough explaination, Steven.

On 13/09/2010 13.59, Steven D'Aprano wrote:

On Mon, 13 Sep 2010 08:55:46 pm Francesco Loffredo wrote:

I don't like this rough behaviour of int(), spitting out an
exception if given a legitimate string representation of a float. Can
some of you Tutors explain me why it must be so?


The int() function behaves as a constructor, producing an integer object
from its argument. It has two jobs:

(1) truncate (round-to-zero) numbers to a whole number by dropping any
fraction part without rounding; and

(2) convert strings to an integer.


So int() can truncate all of these numbers:
...
Okay, that's numbers out of the way. Pretty straightforward.

When it comes to strings, we're doing *conversions*, not truncation, so
we need to decide what are the rules for converting strings. The usual
rule is that, apart from a possible leading + or - sign, we expect a
string of digits. Nobody expects int("two hundred and thirty-seven") to
return 237. What digits are allowed? That depends on the base -- Python
supports bases from 2 to 36:


int("123")  # base 10 is the default

123

int("123ff", 16)  # hexadecimal

74751

int("123ff", 36)

1777371

There's also a "base 0", which uses the string's prefix to specify the
base:


int("0x123ff", 0)  # 0x... means a hex number

74751


So what are we to make of a string like "1.95"? Obviously it's not an
integer, and "." is not a valid digit. If you, the programmer, are
reading in data from a file and are expecting *integers*, and somebody
slipped in a decimal-point, that is just as troublesome as if they
slipped in a semi-colon or the letter Z. Should "1.95" be truncated to
1, or rounded to 2? Should it remain a float? Should the dot be
interpreted as a digit in some unusual base?

Python refuses to guess what int("1.95") should mean, and it raises an
error, just as it does for int("1+1") or int("two").


I understand this, but I don't quite agree. I mean, I don't think 
there's anything to guess. There is no ambiguity in "3.72". As far as I 
know, there is no base, between 2 and 36, in which "." represents a 
valid digit. So it would be *very* easy to do what float() does, then 
truncate as int() already does. Anyway, now that I know, I could always 
use int(float(x))... even if I find it weird.


Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3130 -  Data di rilascio: 
09/12/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wierd replace problem

2010-09-13 Thread Michael Powe
Hello,

In your script, you need to escape each backslash, in order to have it
come out correctly to the interpreter.  IOW, in the shell, '\\' is
what is being processed.  But in your script, you want to send '\\' to
the shell, and in order to do that, you have to escape each backslash,
or ''.  

In a script, '\\' means 'send through a backslash' for shell
processing. The left-most backslash is escaping the one to its right. 

Thanks.

mp

On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
> 
> Hello, 
> 
> I have this string called test with the contents of 'het is een wonder \\TIS'
> 
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS' 
> So that's right.
> 
> Now I try the same in a IDE with this programm :
>  
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items 
>  
> But now Im gettting this output :
>  
> [('"\'tis', 1), 
>  
> Why does the \ stays here. It should have gone as the test in the python 
> prompt says.
>  
> Roelof
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"...we built a new continent in cyberspace where we could go live and be
free. And the nice thing is that, because we built it, we didn't have
to steal it from aboriginal peoples. It was completely empty, and we
invite everyone to live there with us. No immigration restrictions.
There's room for everyone in the world. Come live in the free world
and be free. That's our idea."  -- Richard Stallman


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


Re: [Tutor] Documenting a Module

2010-09-13 Thread Michael Powe
On Mon, Sep 13, 2010 at 12:03:27PM +0200, r...@schoenian-online.de wrote:
> 
> Hi Michael,
> ??
> I can recommend epydoc. You can find it here:
> ??http://epydoc.sourceforge.net/??It's a nice tool and you should have no 
> problems
> with the installation.
> ??
> Ralf
> ??
> ??
> ??

Thank you, much appreciated.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA


47.3% of all statistics are made up on the spot. - Steven Wright


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


Re: [Tutor] classmethod, staticmethod functions (decorator related)

2010-09-13 Thread Huy Ton That
Thank you all,

I was taking a look at the module decimal.py as you cited, and it makes
sense now. Looks very useful to make tools without having to instantiate
anything.

On Mon, Sep 13, 2010 at 7:05 AM, Steven D'Aprano wrote:

> On Mon, 13 Sep 2010 12:29:07 pm Huy Ton That wrote:
> > Hm, thanks guys; I just had to verify I was thinking sanely about it.
> > I am going to pick up classmethods next. Do any of you have common
> > design patterns for the usage. They are just items I haven't
> > integrated in my coding, and I want to be certain I'm off on the
> > right foot (:
>
> The most common use for classmethods is to implement alternative
> constructors. For example, in the Decimal class starting in version 2.7
> and 3.1, you have two constructors:
>
> >>> from decimal import Decimal
> >>> Decimal("1.2345")
> Decimal('1.2345')
> >>> Decimal.from_float(1.2345)
> Decimal('1.2344307220832633902318775653839111328125')
>
> from_float is a class method.
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wierd replace problem

2010-09-13 Thread bob gailer

 On 9/13/2010 8:19 AM, Roelof Wobben wrote:

Hello,

I have this string called test with the contents of 'het is een wonder \\TIS'

Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
And I get at the python prompt this answer : 'het is een wonder TIS'
So that's right.

Now I try the same in a IDE with this programm :

woorden =[]
letter_counts = {}
file = open ('alice_in_wonderland.txt', 'r')
for line in file:
 line2 = line.replace ("\\","")
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
letter_items = letter_counts.items()
letter_items.sort()
print letter_items

But now Im gettting this output :

[('"\'tis', 1),

Why does the \ stays here. It should have gone as the test in the python prompt 
says.
I ran your program against a 1 line file containing 'het is een wonder 
\\TIS'
The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1), 
('wonder', 1)]


Dunno why you are getting a different result.

Here is where using the debugger and going step by step can help. I have 
no experience with the IDLE debugger. Perhaps others can offer advice on 
that.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


[Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: bgai...@gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 15:19:12 +
>
>
>
>
> 
>> Date: Mon, 13 Sep 2010 11:07:19 -0400
>> From: bgai...@gmail.com
>> To: tutor@python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>> On 9/13/2010 8:19 AM, Roelof Wobben wrote:
>>> Hello,
>>>
>>> I have this string called test with the contents of 'het is een wonder 
>>> \\TIS'
>>>
>>> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', 
>>> '')
>>> And I get at the python prompt this answer : 'het is een wonder TIS'
>>> So that's right.
>>>
>>> Now I try the same in a IDE with this programm :
>>>
>>> woorden =[]
>>> letter_counts = {}
>>> file = open ('alice_in_wonderland.txt', 'r')
>>> for line in file:
>>> line2 = line.replace ("\\","")
>>> line3 = line2.lower()
>>> woorden = line3.split()
>>> for letter in woorden:
>>> letter_counts[letter] = letter_counts.get (letter, 0) + 1
>>> letter_items = letter_counts.items()
>>> letter_items.sort()
>>> print letter_items
>>>
>>> But now Im gettting this output :
>>>
>>> [('"\'tis', 1),
>>>
>>> Why does the \ stays here. It should have gone as the test in the python 
>>> prompt says.
>> I ran your program against a 1 line file containing 'het is een wonder
>> \\TIS'
>> The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1),
>> ('wonder', 1)]
>>
>> Dunno why you are getting a different result.
>>
>> Here is where using the debugger and going step by step can help. I have
>> no experience with the IDLE debugger. Perhaps others can offer advice on
>> that.
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Hello everyone.

Chancing to (r\\, '') or (, '') did not help.

I know that there were more outcome. I would only let see that on the python 
prompt the \ is deleted and if I use Eclipse the / stays when I use the text 
from alice in wonderland.

 And im still wondering why this happens.
 Maybe put the text from alice into the python prompt and look what happens.

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


[Tutor] Fwd: RE: wierd replace problem

2010-09-13 Thread bob gailer

 Forwarding to the list.












 Date: Mon, 13 Sep 2010 11:07:19 -0400
 From: bgai...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem

 On 9/13/2010 8:19 AM, Roelof Wobben wrote:

 Hello,

 I have this string called test with the contents of 'het is een wonder \\TIS'

 Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 Now I try the same in a IDE with this programm :

 woorden =[]
 letter_counts = {}
 file = open ('alice_in_wonderland.txt', 'r')
 for line in file:
 line2 = line.replace ("\\","")
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 But now Im gettting this output :

 [('"\'tis', 1),

 Why does the \ stays here. It should have gone as the test in the python 
prompt says.

 I ran your program against a 1 line file containing 'het is een wonder
 \\TIS'
 The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1),
 ('wonder', 1)]

 Dunno why you are getting a different result.

 Here is where using the debugger and going step by step can help. I have
 no experience with the IDLE debugger. Perhaps others can offer advice on
 that.
 istinfo/tutor



Hello everyone.

Chancing to (r\\, '') or (, '') did not help.

I know that there were more outcome. I would only let see that on the python 
prompt the \ is deleted and if I use Eclipse the / stays when I use the text 
from alice in wonderland.

And im still wondering why this happens.
Maybe put the text from alice into the python prompt and look what happens.

Roelof


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


[Tutor] Serial communication ...

2010-09-13 Thread Markus Hubig
Hi @all!

I'm about to write a class for serial communication on Win32 and Linux which
provides a method called "talk" to send something over the serial line,
wait for
the answer and returns it. My problem is, that I don't know how long the
answer
will be (ok max 260 bytes but most answers are much smaller).

This is what I have now, please leave some comments:

   1. Will this work on Win32 (with select)?
   2. Should I better use twisted.internet.serialport?
   3. Will self.read(260)block until it reads the full 260 bytes?

class SerialDevice(Serial):

def __init__(self,port):
Serial.__init__(self)
self.port = port
self.baudrate = 57600
self.bytesize = EIGHTBITS
self.parity = PARITY_ODD
self.stopbits = STOPBITS_TWO
self.timeout = 0
self.xonxoff = 0
self.rtscts = 0
self.dsrdtr = 0
self.open()
self.flush()

def _write(self, packet):
fileno = self.fileno()
while True:
readable, writeable, excepts = select( [], [fileno], [], 0.2 )
if fileno in writeable:
time.sleep(0.1)
length = self.write(packet)
break
return length

def _read(self):
fileno = self.fileno()
while True:
readable, writeable, excepts = select( [], [fileno], [], 0.2 )
if fileno in readable:
time.sleep(0.1)
packet = self.read(260)
break
return packet

def talk(self, packet):
self._write(packet)
responce = self._read()
return responce

Thank you, Markus

-- 
Can't read my mail? Just don't hold it that way!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wierd replace problem

2010-09-13 Thread Michael Powe
On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
> 
> Hello, 
> 
> I have this string called test with the contents of 'het is een wonder \\TIS'
> 
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS' 
> So that's right.
> 
> Now I try the same in a IDE with this programm :
>  
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items 
>  
> But now Im gettting this output :
>  
> [('"\'tis', 1), 
>  
> Why does the \ stays here. It should have gone as the test in the python 
> prompt says.

Hello,

Actually, on closer look I can see the answer.

The original text must look something like this:

\\"'tis the season to be jolly," said santa.

When you run your process against a string in that format, you get the
output shown: ('"\'tis', 1).  The appearance of the backslash is
fortuitous.  It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string.  IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
"I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath." -- H.B. Stowe


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


Re: [Tutor] Documenting a Module

2010-09-13 Thread Michael Powe
On Mon, Sep 13, 2010 at 12:03:27PM +0200, r...@schoenian-online.de wrote:
> 
> Hi Michael,

> I can recommend epydoc. You can find it here:
> ??http://epydoc.sourceforge.net/??It's a nice tool and you should
> have no problems with the installation.

> Ralf

Hello,

I just want to follow up that epydoc is completely awesome and exactly
the right tool for the job.  I was able to get my doc generated and
wrapped up nicely in less time than I spent trying to get Sphinx
installed yesterday.

Thanks.

mp

-- 
Michael Powemich...@trollope.orgNaugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and ; let
him come out as I do, and . -- Samuel Johnson


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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




Date: Mon, 13 Sep 2010 12:17:47 -0400
From: mich...@trollope.org
To: tutor@python.org
Subject: Re: [Tutor] wierd replace problem


On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
>
> Hello,
>
> I have this string called test with the contents of 'het is een wonder \\TIS'
>
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS'
> So that's right.
>
> Now I try the same in a IDE with this programm :
>
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items
>
> But now Im gettting this output :
>
> [('"\'tis', 1),
>
> Why does the \ stays here. It should have gone as the test in the python 
> prompt says.

Hello,

Actually, on closer look I can see the answer.

The original text must look something like this:

\\"'tis the season to be jolly," said santa.

When you run your process against a string in that format, you get the
output shown: ('"\'tis', 1). The appearance of the backslash is
fortuitous. It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string. IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.

Thanks.

mp

--
Michael Powe mich...@trollope.org Naugatuck CT USA
"I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath." -- H.B. Stowe

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

 
Hello Michael,
 
The original text is this : 
 
`'Tis so,' said the Duchess:  `and the moral of that is--"Oh,
'tis love, 'tis love, that makes the world go round!"'

So I think I have to replace the '.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] wierd replace problem

2010-09-13 Thread Joel Goldstick
On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben  wrote:

>
>
>
> 
> Date: Mon, 13 Sep 2010 12:17:47 -0400
> From: mich...@trollope.org
> To: tutor@python.org
> Subject: Re: [Tutor] wierd replace problem
>
>
> On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
> >
> > Hello,
> >
> > I have this string called test with the contents of 'het is een wonder
> \\TIS'
> >
> > Now I want to get rid of the \\ so I do this : test2 = test.replace
> ('\\', '')
> > And I get at the python prompt this answer : 'het is een wonder TIS'
> > So that's right.
> >
> > Now I try the same in a IDE with this programm :
> >
> > woorden =[]
> > letter_counts = {}
> > file = open ('alice_in_wonderland.txt', 'r')
> > for line in file:
> > line2 = line.replace ("\\","")
> > line3 = line2.lower()
> > woorden = line3.split()
> > for letter in woorden:
> > letter_counts[letter] = letter_counts.get (letter, 0) + 1
> > letter_items = letter_counts.items()
> > letter_items.sort()
> > print letter_items
> >
> > But now Im gettting this output :
> >
> > [('"\'tis', 1),
> >
> > Why does the \ stays here. It should have gone as the test in the python
> prompt says.
>
> Hello,
>
> Actually, on closer look I can see the answer.
>
> The original text must look something like this:
>
> \\"'tis the season to be jolly," said santa.
>
> When you run your process against a string in that format, you get the
> output shown: ('"\'tis', 1). The appearance of the backslash is
> fortuitous. It has nothing to do with the string.replace(), it's
> there to escape the single quote, which is appearing in the middle of
> a single-quoted string. IF the double-quote had not also been there,
> python would have replaced the outer quotes with double quotes, as it
> does on my system before I got to thinking about that lonely double
> quote.
>
> Thanks.
>
> mp
>
> --
> Michael Powe mich...@trollope.org Naugatuck CT USA
> "I wrote what I did because as a woman, as a mother, I was oppressed
> and brokenhearted with the sorrows and injustice I saw, because as a
> Christian I felt the dishonor to Christianity, -- because as a lover
> of my country, I trembled at the coming day of wrath." -- H.B. Stowe
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
> Hello Michael,
>
> The original text is this :
>
> `'Tis so,' said the Duchess:  `and the moral of that is--"Oh,
> 'tis love, 'tis love, that makes the world go round!"'
>
> So I think I have to replace the '.
>
> Roelof
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


That is a completely different problem than the one you originally posed.  I
doubt that what you inserted above is actually completely correct.  It opens
with  a back tick, has a back tick before and, then ens with what looks like
a double quote then a single quote
-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: joel.goldst...@gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 16:45:28 +
>
>
>
>
> 
>> Date: Mon, 13 Sep 2010 12:42:56 -0400
>> From: joel.goldst...@gmail.com
>> To: tutor@python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>>
>>
>> On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben
>>> wrote:
>>
>>
>>
>> 
>> Date: Mon, 13 Sep 2010 12:17:47 -0400
>> From: mich...@trollope.org
>> To: tutor@python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>>
>> On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:
>>>
>>> Hello,
>>>
>>> I have this string called test with the contents of 'het is een
>> wonder \\TIS'
>>>
>>> Now I want to get rid of the \\ so I do this : test2 = test.replace
>> ('\\', '')
>>> And I get at the python prompt this answer : 'het is een wonder TIS'
>>> So that's right.
>>>
>>> Now I try the same in a IDE with this programm :
>>>
>>> woorden =[]
>>> letter_counts = {}
>>> file = open ('alice_in_wonderland.txt', 'r')
>>> for line in file:
>>> line2 = line.replace ("\\","")
>>> line3 = line2.lower()
>>> woorden = line3.split()
>>> for letter in woorden:
>>> letter_counts[letter] = letter_counts.get (letter, 0) + 1
>>> letter_items = letter_counts.items()
>>> letter_items.sort()
>>> print letter_items
>>>
>>> But now Im gettting this output :
>>>
>>> [('"\'tis', 1),
>>>
>>> Why does the \ stays here. It should have gone as the test in the
>> python prompt says.
>>
>> Hello,
>>
>> Actually, on closer look I can see the answer.
>>
>> The original text must look something like this:
>>
>> \\"'tis the season to be jolly," said santa.
>>
>> When you run your process against a string in that format, you get the
>> output shown: ('"\'tis', 1). The appearance of the backslash is
>> fortuitous. It has nothing to do with the string.replace(), it's
>> there to escape the single quote, which is appearing in the middle of
>> a single-quoted string. IF the double-quote had not also been there,
>> python would have replaced the outer quotes with double quotes, as it
>> does on my system before I got to thinking about that lonely double
>> quote.
>>
>> Thanks.
>>
>> mp
>>
>> --
>> Michael Powe mich...@trollope.org
>> Naugatuck CT USA
>> "I wrote what I did because as a woman, as a mother, I was oppressed
>> and brokenhearted with the sorrows and injustice I saw, because as a
>> Christian I felt the dishonor to Christianity, -- because as a lover
>> of my country, I trembled at the coming day of wrath." -- H.B. Stowe
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> Hello Michael,
>>
>> The original text is this :
>>
>> `'Tis so,' said the Duchess: `and the moral of that is--"Oh,
>> 'tis love, 'tis love, that makes the world go round!"'
>>
>> So I think I have to replace the '.
>>
>> Roelof
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> That is a completely different problem than the one you originally
>> posed. I doubt that what you inserted above is actually completely
>> correct. It opens with a back tick, has a back tick before and, then
>> ens with what looks like a double quote then a single quote
>> --
>> Joel Goldstick
>>
>>
>> ___ Tutor maillist -
>> Tutor@python.org To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Hello Joel,

The orginal text can be found here : 
http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
So you can see I copied it right.

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: tutor@python.org
> Date: Mon, 13 Sep 2010 16:46:09 +
> Subject: [Tutor] wierd replace problem
>
>
>
>
> 
>> From: rwob...@hotmail.com
>> To: joel.goldst...@gmail.com
>> Subject: RE: [Tutor] wierd replace problem
>> Date: Mon, 13 Sep 2010 16:45:28 +
>>
>>
>>
>>
>> 
>>> Date: Mon, 13 Sep 2010 12:42:56 -0400
>>> From: joel.goldst...@gmail.com
>>> To: tutor@python.org
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>>
>>>
>>> On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben
 wrote:
>>>
>>>
>>>
>>> 
>>> Date: Mon, 13 Sep 2010 12:17:47 -0400
>>> From: mich...@trollope.org
>>> To: tutor@python.org
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>>
>>> On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:

 Hello,

 I have this string called test with the contents of 'het is een
>>> wonder \\TIS'

 Now I want to get rid of the \\ so I do this : test2 = test.replace
>>> ('\\', '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 Now I try the same in a IDE with this programm :

 woorden =[]
 letter_counts = {}
 file = open ('alice_in_wonderland.txt', 'r')
 for line in file:
 line2 = line.replace ("\\","")
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 But now Im gettting this output :

 [('"\'tis', 1),

 Why does the \ stays here. It should have gone as the test in the
>>> python prompt says.
>>>
>>> Hello,
>>>
>>> Actually, on closer look I can see the answer.
>>>
>>> The original text must look something like this:
>>>
>>> \\"'tis the season to be jolly," said santa.
>>>
>>> When you run your process against a string in that format, you get the
>>> output shown: ('"\'tis', 1). The appearance of the backslash is
>>> fortuitous. It has nothing to do with the string.replace(), it's
>>> there to escape the single quote, which is appearing in the middle of
>>> a single-quoted string. IF the double-quote had not also been there,
>>> python would have replaced the outer quotes with double quotes, as it
>>> does on my system before I got to thinking about that lonely double
>>> quote.
>>>
>>> Thanks.
>>>
>>> mp
>>>
>>> --
>>> Michael Powe mich...@trollope.org
>>> Naugatuck CT USA
>>> "I wrote what I did because as a woman, as a mother, I was oppressed
>>> and brokenhearted with the sorrows and injustice I saw, because as a
>>> Christian I felt the dishonor to Christianity, -- because as a lover
>>> of my country, I trembled at the coming day of wrath." -- H.B. Stowe
>>>
>>> ___
>>> Tutor maillist - Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> Hello Michael,
>>>
>>> The original text is this :
>>>
>>> `'Tis so,' said the Duchess: `and the moral of that is--"Oh,
>>> 'tis love, 'tis love, that makes the world go round!"'
>>>
>>> So I think I have to replace the '.
>>>
>>> Roelof
>>>
>>> ___
>>> Tutor maillist - Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> That is a completely different problem than the one you originally
>>> posed. I doubt that what you inserted above is actually completely
>>> correct. It opens with a back tick, has a back tick before and, then
>>> ens with what looks like a double quote then a single quote
>>> --
>>> Joel Goldstick
>>>
>>>
>>> ___ Tutor maillist -
>>> Tutor@python.org To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Hello Joel,
>
> The orginal text can be found here : 
> http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
> So you can see I copied it right.
>
> Roelof
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I tried my programm in IDLE and the problem stays.
So I think it has to do with the text-file and how python reads it.
 
Roelof

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


Re: [Tutor] classmethod, staticmethod functions (decorator related)

2010-09-13 Thread Alan Gauld


"Huy Ton That"  wrote

I was taking a look at the module decimal.py as you cited, and it 
makes
sense now. Looks very useful to make tools without having to 
instantiate

anything.


Thats not a good way to think of them.
Doing things without instantiating is usually better done by a 
function.


Class methods are for doing things to the class.
eg you might use one to get a count of all the instances - or even a 
list.

Or you might want to reset the status of a group of instances. Or find
a particular instance out of all existing ones, and if its not there
create a new instance and return it.

Class methhods are often commonly used for providing persistence
mechanisms with databases or marshalling pools for network programming
etc etc.


The most common use for classmethods is to implement alternative
constructors. For example, in the Decimal class starting in version 
2.7

and 3.1, you have two constructors:


Whilst I'd question if its *the most common* it is certainly another 
valid

use for them in Python which doesn't offer multiple constructors as
standard. This is rather like the factory methods of Objective C.

I've rarely worked on any significant OOP project that did not use
class methods somewhere in its design. But they tend not to be used
in the typical small-scale code used in tutorials, so it's hard for a 
newbie

to really get a feel for how they are used and why.

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Alan Gauld


"Roelof Wobben"  wrote

Now I want to get rid of the \\ so I do this : test2 = test.replace 
('\\', '')

And I get at the python prompt this answer : 'het is een wonder TIS'
So that's right.


OK,. Thats replacing a double slash in the data


for line in file:
   line2 = line.replace ("\\","")


And this is doing the same. Any double slashes in your file content
will be replaced.


letter_items = letter_counts.items()
letter_items.sort()
print letter_items


Now we have an issue of representing characters.


[('"\'tis', 1),


This is a representation issue. Python is using the \ to escape
the single quote since you are using single quotes on the outside.
Without the backslash the \' would look like the end of the
string to Python.

If you print the actual string it will not show the quote:

for item in letter_items:
   print item[0]

Backslashes are awkward characters because they are used
for several different special purposes as well as being characters
in their own right. If you had tried replacing almost any other
character you would not have gotten confused.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





Why does the \ stays here. It should have gone as the test in the 
python prompt says.


Roelof



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




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


Re: [Tutor] wierd replace problem

2010-09-13 Thread bob gailer

 On 9/13/2010 12:58 PM, Roelof Wobben wrote:


  The orginal text can be found here : 
http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt


There are no \ in that text!


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Mon, 13 Sep 2010 18:28:46 +0100
> Subject: Re: [Tutor] wierd replace problem
>
>
> "Roelof Wobben" wrote
>
>> Now I want to get rid of the \\ so I do this : test2 = test.replace
>> ('\\', '')
>> And I get at the python prompt this answer : 'het is een wonder TIS'
>> So that's right.
>
> OK,. Thats replacing a double slash in the data
>
>> for line in file:
>> line2 = line.replace ("\\","")
>
> And this is doing the same. Any double slashes in your file content
> will be replaced.
>
>> letter_items = letter_counts.items()
>> letter_items.sort()
>> print letter_items
>
> Now we have an issue of representing characters.
>
>> [('"\'tis', 1),
>
> This is a representation issue. Python is using the \ to escape
> the single quote since you are using single quotes on the outside.
> Without the backslash the \' would look like the end of the
> string to Python.
>
> If you print the actual string it will not show the quote:
>
> for item in letter_items:
> print item[0]
>
> Backslashes are awkward characters because they are used
> for several different special purposes as well as being characters
> in their own right. If you had tried replacing almost any other
> character you would not have gotten confused.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>>
>> Why does the \ stays here. It should have gone as the test in the
>> python prompt says.
>>
>> Roelof
>>
>>
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
hello Alan, 
 
Your right. Then it prints like this "'tis
Which is not right. It must be tis.
So the replace does not what it supposed to do.
 
Roelof

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread bob gailer

 On 9/13/2010 1:50 PM, Roelof Wobben wrote:

[snip]

hello Alan,

Your right. Then it prints like this "'tis
Which is not right. It must be tis.
So the replace does not what it supposed to do.

Sorry but I am now more confused. After discovering no \ in the text 
file now you seem to have have a new specification, which is to get rid 
of the '.


I suggest you give a clear, complete and correct problem statement. 
Right now we are shooting in the dark at a moving target.


Something like.

Given the file alice_in_wonderland.txt, copied from url so-and-so

Remove these characters ...

Split into words (not letters?) where word is defined as

Count the frequency of each word.

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Joel Goldstick
On Mon, Sep 13, 2010 at 2:08 PM, bob gailer  wrote:

>  On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>
> [snip]
>
>  hello Alan,
>>
>> Your right. Then it prints like this "'tis
>> Which is not right. It must be tis.
>> So the replace does not what it supposed to do.
>>
>>  Sorry but I am now more confused. After discovering no \ in the text file
> now you seem to have have a new specification, which is to get rid of the '.
>
> I suggest you give a clear, complete and correct problem statement. Right
> now we are shooting in the dark at a moving target.
>
> Something like.
>
> Given the file alice_in_wonderland.txt, copied from url so-and-so
>
> Remove these characters ...
>
> Split into words (not letters?) where word is defined as
>
> Count the frequency of each word.
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

How about using str.split() to put words in a list, then run strip() over
each word with the required characters to be removed ('`")

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


[Tutor] FW: wierd replace problem

2010-09-13 Thread Roelof Wobben





> From: rwob...@hotmail.com
> To: bgai...@gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 18:19:43 +
>
>
>
>
> 
>> Date: Mon, 13 Sep 2010 14:08:46 -0400
>> From: bgai...@gmail.com
>> To: tutor@python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>> On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>>
>> [snip]
>>> hello Alan,
>>>
>>> Your right. Then it prints like this "'tis
>>> Which is not right. It must be tis.
>>> So the replace does not what it supposed to do.
>>>
>> Sorry but I am now more confused. After discovering no \ in the text
>> file now you seem to have have a new specification, which is to get rid
>> of the '.
>>
>> I suggest you give a clear, complete and correct problem statement.
>> Right now we are shooting in the dark at a moving target.
>>
>> Something like.
>>
>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>
>> Remove these characters ...
>>
>> Split into words (not letters?) where word is defined as
>>
>> Count the frequency of each word.
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Hello,
>
> The problem as stated in the book is :
>

3.Write a program called alice_words.py that creates a text file named 
alice_words.txt containing an alphabetical listing of all the words found in 
alice_in_wonderland.txt together with the number of times each word occurs. The 
first 10 lines of your output file should look something like this:
Word Count
===
a 631
a-piece 1
abide 1
able 1
about 94
above 3
absence 1
absurd 2How many times does the word, alice, occur in the book?

The text can be found here : 
http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt

So I open the file.
Read the first rule.

This is no problem for me.

Then I want to remove some characters like ' , " when the word in the text 
begins with these characters.
And there is the problem. The ' and " can't be removed with replace.
So in the output you will see something like this "dark instead of dark

word is the words of the sentence which is read in from the text-file.

Am i now clear what the problem is Im facing.

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


[Tutor] FW: wierd replace problem

2010-09-13 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: joel.goldst...@gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 18:23:36 +
>
>
>
>
> 
>> Date: Mon, 13 Sep 2010 14:18:36 -0400
>> From: joel.goldst...@gmail.com
>> To: tutor@python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>>
>>
>> On Mon, Sep 13, 2010 at 2:08 PM, bob gailer
>>> wrote:
>> On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>>
>> [snip]
>>
>> hello Alan,
>>
>> Your right. Then it prints like this "'tis
>> Which is not right. It must be tis.
>> So the replace does not what it supposed to do.
>>
>> Sorry but I am now more confused. After discovering no \ in the text
>> file now you seem to have have a new specification, which is to get rid
>> of the '.
>>
>> I suggest you give a clear, complete and correct problem statement.
>> Right now we are shooting in the dark at a moving target.
>>
>> Something like.
>>
>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>
>> Remove these characters ...
>>
>> Split into words (not letters?) where word is defined as
>>
>> Count the frequency of each word.
>>
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>> ___
>> Tutor maillist - Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> How about using str.split() to put words in a list, then run strip()
>> over each word with the required characters to be removed ('`")
>>
>> --
>> Joel Goldstick
>>
>>
>> ___ Tutor maillist -
>> Tutor@python.org To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Hello Joel.

That can be a solution but when i have --dark the -- must be removed.
But in a-piece the - must not be removed.

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


Re: [Tutor] Serial communication ...

2010-09-13 Thread Markus Hubig
On Mon, Sep 13, 2010 at 6:10 PM, André da Palma  wrote:

> Last year i was working with serial communication as well and there is
> already a library for python, i guess it's pySerial. Try to google it,
> perhaps

it can be useful for you.


Yes you're totally right! And that's the package im using im my posted code,
but im about to customize Serial class a litte bit. My code actually starts
with:

from serial import Serial, SerialExceptionfrom serial import
EIGHTBITS, PARITY_ODD, STOPBITS_TWO

And inherits from serial.Serial:

class SerialDevice(Serial):def __init__(self,port):
Serial.__init__(self)

And serial is the module name of pyserial 
 ...

How did you sense the end the stuff you're receiving via the serial line?

- Markus

-- 
Can't read my mail? Just don't hold it that way!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Brian Jones
I've been coding Python long enough that 'asking forgiveness instead of
permission' is my first instinct, but the resulting code is sometimes
clumsy, and I wonder if someone can suggest something I'm missing, or at
least validate what's going on here in some way.

What I'm trying to do is write a file to a directory. However, the directory
may not exist the first time I try to write a file there, so I'm going to
first try to write the file, and if I get an exception, create the directory
(er, *try* to), and *then* write the file there. Here's my first shot at the
code:

try:
self.save_file(picfile_fullpath, picdata)
except IOError as err:
# directory doesn't exist. Try to create it.
try:
os.makedirs(picfile_fullpath)
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" %
(picfile_fullpath, oserr))
else:
# Created dir, now write file.
try:
self.save_file(picfile_fullpath, picdata)
except IOError as err:
logging.error("Bailing. Couldn't save file %s (%s)" %
(picfile_fullpath, err))
return False

Doesn't this seem less readable than the 'ask permission' equivalent? I
think it does, but in this case asking permission for every single operation
when the dir will only need to be created a single time (and then may be
written to several hundred times) is pretty wasteful.

I suppose I could set some sentinel variable and check for it in a while
loop, but then I need some other scaffolding code to make sure I don't
infinitely loop trying to create the directory, and probably some other
stuff I'm forgetting, so it strikes me as being just as messy.

Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian



-- 
Brian K. Jones
My Blog  http://www.protocolostomy.com
Follow me  http://twitter.com/bkjones
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Serial communication ...

2010-09-13 Thread Adam Bark

On 13/09/10 16:36, Markus Hubig wrote:

Hi @all!

I'm about to write a class for serial communication on Win32 and Linux 
which
provides a method called "talk" to send something over the serial 
line, wait for
the answer and returns it. My problem is, that I don't know how long 
the answer

will be (ok max 260 bytes but most answers are much smaller).

This is what I have now, please leave some comments:

   1. Will this work on Win32 (with select)?
   2. Should I better use twisted.internet.serialport?
   3. Will self.read(260)block until it reads the full 260 bytes?

class SerialDevice(Serial):

def __init__(self,port):
Serial.__init__(self)
self.port = port
self.baudrate = 57600
self.bytesize = EIGHTBITS
self.parity = PARITY_ODD
self.stopbits = STOPBITS_TWO
self.timeout = 0
self.xonxoff = 0
self.rtscts = 0
self.dsrdtr = 0
self.open()
self.flush()
def _write(self, packet):
fileno = self.fileno()
while True:
readable, writeable, excepts = select( [], [fileno], [], 0.2 )
if fileno in writeable:
time.sleep(0.1)
length = self.write(packet)
break
return length
def _read(self):
fileno = self.fileno()
while True:
readable, writeable, excepts = select( [], [fileno], [], 0.2 )
if fileno in readable:
time.sleep(0.1)
packet = self.read(260)
break
return packet
def talk(self, packet):
self._write(packet)
responce = self._read()
return responce

Thank you, Markus

--
Can't read my mail? Just don't hold it that way!
Ideally you would send a specific ending packet and you read one byte at 
a time until the right sequence comes up. Alternatively you could have 
the first byte as a length indicator. The only other options I can think 
of are fixed length or a specific timeout.

HTH.

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


Re: [Tutor] Serial communication ...

2010-09-13 Thread Emile van Sebille

On 9/13/2010 8:36 AM Markus Hubig said...

Hi @all!

I'm about to write a class for serial communication on Win32 and Linux which
provides a method called "talk" to send something over the serial line,
wait for
the answer and returns it. My problem is, that I don't know how long the
answer
will be (ok max 260 bytes but most answers are much smaller).

This is what I have now, please leave some comments:

1. Will this work on Win32 (with select)?
2. Should I better use twisted.internet.serialport?
3. Will self.read(260)block until it reads the full 260 bytes?



You're subclassing Serial -- the answers to your questions depend on 
what that is.  So, what is it? Does it support windows? Has anyone 
compared/contrasted it to twisted.internet.serialport?  What does its 
read do?  And finally, perhaps, does it have it's own support 
group/list?  You'll probably get better answers directly from there than 
here.


HTH,

Emile





class SerialDevice(Serial):

 def __init__(self,port):
 Serial.__init__(self)
 self.port = port
 self.baudrate = 57600
 self.bytesize = EIGHTBITS
 self.parity = PARITY_ODD
 self.stopbits = STOPBITS_TWO
 self.timeout = 0
 self.xonxoff = 0
 self.rtscts = 0
 self.dsrdtr = 0
 self.open()
 self.flush()

 def _write(self, packet):
 fileno = self.fileno()
 while True:
 readable, writeable, excepts = select( [], [fileno], [], 0.2 )
 if fileno in writeable:
 time.sleep(0.1)
 length = self.write(packet)
 break
 return length

 def _read(self):
 fileno = self.fileno()
 while True:
 readable, writeable, excepts = select( [], [fileno], [], 0.2 )
 if fileno in readable:
 time.sleep(0.1)
 packet = self.read(260)
 break
 return packet

 def talk(self, packet):
 self._write(packet)
 responce = self._read()
 return responce

Thank you, Markus




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



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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Emile van Sebille

On 9/13/2010 11:31 AM Brian Jones said...

I've been coding Python long enough that 'asking forgiveness instead of
permission' is my first instinct, but the resulting code is sometimes
clumsy, and I wonder if someone can suggest something I'm missing, or at
least validate what's going on here in some way.

What I'm trying to do is write a file to a directory. However, the directory
may not exist the first time I try to write a file there, so I'm going to
first try to write the file, and if I get an exception, create the directory
(er, *try* to), and *then* write the file there. Here's my first shot at the
code:

 try:
 self.save_file(picfile_fullpath, picdata)
 except IOError as err:
 # directory doesn't exist. Try to create it.
 try:
 os.makedirs(picfile_fullpath)
 except OSError as oserr:
 logging.error("Can't create file path: %s (%s)" %
(picfile_fullpath, oserr))
 else:
 # Created dir, now write file.
 try:
 self.save_file(picfile_fullpath, picdata)
 except IOError as err:
 logging.error("Bailing. Couldn't save file %s (%s)" %
(picfile_fullpath, err))
 return False


Unless this is in a tight loop, I think I'd write:

try:
os.makedirs(picfile_fullpath)
try:
self.save_file(picfile_fullpath, picdata)
return True
# all/only error handling code follows.
except IOError as err:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

return False
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

return False

which eliminates the duplicated save_file step.



Doesn't this seem less readable than the 'ask permission' equivalent? I
think it does, but in this case asking permission for every single operation
when the dir will only need to be created a single time (and then may be
written to several hundred times) is pretty wasteful.


Agreed -- if it's in a loop, you'd want to only check once.  Of course, 
if the directory is eg an nfs share, continued access could be an issue.


HTH,

Emile




I suppose I could set some sentinel variable and check for it in a while
loop, but then I need some other scaffolding code to make sure I don't
infinitely loop trying to create the directory, and probably some other
stuff I'm forgetting, so it strikes me as being just as messy.

Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian






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



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


Re: [Tutor] Serial communication ...

2010-09-13 Thread Markus Hubig
On Mon, Sep 13, 2010 at 8:33 PM, Adam Bark  wrote:

> Ideally you would send a specific ending packet and you read one byte at a
> time until the
>
right sequence comes up. Alternatively you could have the first byte as a
> length indicator.
>

Oh my dear! You're damn right! The protocol im implementing is fixed so I
can't
at an ending packet, but every message contains an length field I can use
for this!!
How could I miss this?!

Thank you, Markus

-- 
Can't read my mail? Just don't hold it that way!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Adam Bark

On 13/09/10 19:31, Brian Jones wrote:
I've been coding Python long enough that 'asking forgiveness instead 
of permission' is my first instinct, but the resulting code is 
sometimes clumsy, and I wonder if someone can suggest something I'm 
missing, or at least validate what's going on here in some way.


What I'm trying to do is write a file to a directory. However, the 
directory may not exist the first time I try to write a file there, so 
I'm going to first try to write the file, and if I get an exception, 
create the directory (er, *try* to), and *then* write the file there. 
Here's my first shot at the code:


try:
self.save_file(picfile_fullpath, picdata)
except IOError as err:
# directory doesn't exist. Try to create it.
try:
os.makedirs(picfile_fullpath)
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

else:
# Created dir, now write file.
try:
self.save_file(picfile_fullpath, picdata)
except IOError as err:
logging.error("Bailing. Couldn't save file %s 
(%s)" % (picfile_fullpath, err))

return False

Doesn't this seem less readable than the 'ask permission' equivalent? 
I think it does, but in this case asking permission for every single 
operation when the dir will only need to be created a single time (and 
then may be written to several hundred times) is pretty wasteful.


I suppose I could set some sentinel variable and check for it in a 
while loop, but then I need some other scaffolding code to make sure I 
don't infinitely loop trying to create the directory, and probably 
some other stuff I'm forgetting, so it strikes me as being just as messy.


Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian


How about something like this?

try:
os.makedirs(picfile_fullpath)
self.save_file(picfile_fullpath, picdata)
except IOError, OSError as err:
if type(err) is OSError:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

try:
self.save_file(picfile_fullpath, picdata)
except IOError:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

else:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))


This saves you one try except and the else although it adds an if else. 
Either way it's not as far nested.

I just thought up another way that just takes two try excepts:

try:
try:
os.makedirs(picfile_fullpath)
self.save_file(picfile_fullpath, picdata)
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

self.save_file(picfile_fullpath, picdata)
except IOError as err:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

return False

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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Evert Rol
> I've been coding Python long enough that 'asking forgiveness instead of 
> permission' is my first instinct, but the resulting code is sometimes clumsy, 
> and I wonder if someone can suggest something I'm missing, or at least 
> validate what's going on here in some way. 
> 
> What I'm trying to do is write a file to a directory. However, the directory 
> may not exist the first time I try to write a file there, so I'm going to 
> first try to write the file, and if I get an exception, create the directory 
> (er, *try* to), and *then* write the file there.

That would work.
Though I would just try to create the error directory first. If that fails, I 
check the error message/code in the except clause: if it indicates the 
directory already exists, I pass the exception, otherwise reraise it.
Then I continue with creating the file within the directory I now am certain of 
exists.
Note 1: certain is only half: some other process could remove the directory in 
the split second between my code creating it and my code creating the file. If 
you think that could happen, you'll need to look at the other ways to do this.
Note 2: the directory can exist, but not have write access to your process. So 
between the try-except for creating a directory and the try-except for creating 
a file, you may put in a try-except for chmod. Of course, if you're not the 
owner, both the chmod and file creation will fail (I'm assuming some *nix 
platform here, btw).

> Here's my first shot at the code: 
> 
> try:  
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> # directory doesn't exist. Try to create it.

Careful: you're not checking the actually error given by the exception. There 
may be more than one reason that the file can't be created (examples: the 
permissions mentioned above, or some file creation limit in a directory).


> try:  
> os.makedirs(picfile_fullpath)
> except OSError as oserr:
> logging.error("Can't create file path: %s (%s)" % 
> (picfile_fullpath, oserr))
> else: 
> # Created dir, now write file.
> try:  
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> logging.error("Bailing. Couldn't save file %s (%s)" % 
> (picfile_fullpath, err)) 
> return False
> 
> Doesn't this seem less readable than the 'ask permission' equivalent? I think 
> it does, but in this case asking permission for every single operation when 
> the dir will only need to be created a single time (and then may be written 
> to several hundred times) is pretty wasteful.

One of the things I once read (but I forgot where) on this issue, is the usual 
"it depends". It depends whether you except that often, the directory doesn't 
exist and the file can't directly be created. In that case, if may be quicker 
to ask permission first (simple if-statement). If you expect that in general, 
you can immediately create the file within the directory (so an exception is 
unlikely to occur), then use a try-except clause.
But don't take my word for it; I'd be curious what others on this list say 
about this.


> 
> I suppose I could set some sentinel variable and check for it in a while 
> loop, but then I need some other scaffolding code to make sure I don't 
> infinitely loop trying to create the directory, and probably some other stuff 
> I'm forgetting, so it strikes me as being just as messy. 
> 
> Is there a clean sort of pattern to apply in instances like this? 

I guess not, though readability of code is an important thing to consider. In 
this case, I don't find the correctly unreadable, but at some point, these 
things do tend to get out of hand and you're better off coding it differently 
(perhaps even using functions).


  Evert

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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Brian Jones
Thanks for the replies so far. One thing that's probably relevant: once a
directory is created, I can expect to write a couple of hundred files to it,
so doing a 'try os.makedirs' right off the bat strikes me as coding for the
*least* common case instead of the *most* common (which is that the
directory exists and the file write succeeds). If this were a one-off file
write well then things get easier, but I'd like to avoid attempting a
makedirs 100 times when 99 of those times I know it'll give me an error.

brian

On Mon, Sep 13, 2010 at 3:07 PM, Evert Rol  wrote:

> > I've been coding Python long enough that 'asking forgiveness instead of
> permission' is my first instinct, but the resulting code is sometimes
> clumsy, and I wonder if someone can suggest something I'm missing, or at
> least validate what's going on here in some way.
> >
> > What I'm trying to do is write a file to a directory. However, the
> directory may not exist the first time I try to write a file there, so I'm
> going to first try to write the file, and if I get an exception, create the
> directory (er, *try* to), and *then* write the file there.
>
> That would work.
> Though I would just try to create the error directory first. If that fails,
> I check the error message/code in the except clause: if it indicates the
> directory already exists, I pass the exception, otherwise reraise it.
> Then I continue with creating the file within the directory I now am
> certain of exists.
> Note 1: certain is only half: some other process could remove the directory
> in the split second between my code creating it and my code creating the
> file. If you think that could happen, you'll need to look at the other ways
> to do this.
> Note 2: the directory can exist, but not have write access to your process.
> So between the try-except for creating a directory and the try-except for
> creating a file, you may put in a try-except for chmod. Of course, if you're
> not the owner, both the chmod and file creation will fail (I'm assuming some
> *nix platform here, btw).
>
> > Here's my first shot at the code:
> >
> > try:
> > self.save_file(picfile_fullpath, picdata)
> > except IOError as err:
> > # directory doesn't exist. Try to create it.
>
> Careful: you're not checking the actually error given by the exception.
> There may be more than one reason that the file can't be created (examples:
> the permissions mentioned above, or some file creation limit in a
> directory).
>
>
> > try:
> > os.makedirs(picfile_fullpath)
> > except OSError as oserr:
> > logging.error("Can't create file path: %s (%s)" %
> (picfile_fullpath, oserr))
> > else:
> > # Created dir, now write file.
> > try:
> > self.save_file(picfile_fullpath, picdata)
> > except IOError as err:
> > logging.error("Bailing. Couldn't save file %s (%s)" %
> (picfile_fullpath, err))
> > return False
> >
> > Doesn't this seem less readable than the 'ask permission' equivalent? I
> think it does, but in this case asking permission for every single operation
> when the dir will only need to be created a single time (and then may be
> written to several hundred times) is pretty wasteful.
>
> One of the things I once read (but I forgot where) on this issue, is the
> usual "it depends". It depends whether you except that often, the directory
> doesn't exist and the file can't directly be created. In that case, if may
> be quicker to ask permission first (simple if-statement). If you expect that
> in general, you can immediately create the file within the directory (so an
> exception is unlikely to occur), then use a try-except clause.
> But don't take my word for it; I'd be curious what others on this list say
> about this.
>
>
> >
> > I suppose I could set some sentinel variable and check for it in a while
> loop, but then I need some other scaffolding code to make sure I don't
> infinitely loop trying to create the directory, and probably some other
> stuff I'm forgetting, so it strikes me as being just as messy.
> >
> > Is there a clean sort of pattern to apply in instances like this?
>
> I guess not, though readability of code is an important thing to consider.
> In this case, I don't find the correctly unreadable, but at some point,
> these things do tend to get out of hand and you're better off coding it
> differently (perhaps even using functions).
>
>
>  Evert
>
>


-- 
Brian K. Jones
My Blog  http://www.protocolostomy.com
Follow me  http://twitter.com/bkjones
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread davidheiserca


I suggest something like:

try:
   os.makedirs(path)
except:
   pass
open("%s/%s" % (path, filename), 'w').write(filedata)


- Original Message - 
From: "Emile van Sebille" 

To: 
Sent: Monday, September 13, 2010 11:56 AM
Subject: Re: [Tutor] What's the best way to ask forgiveness here?



On 9/13/2010 11:31 AM Brian Jones said...

I've been coding Python long enough that 'asking forgiveness instead of
permission' is my first instinct, but the resulting code is sometimes
clumsy, and I wonder if someone can suggest something I'm missing, or at
least validate what's going on here in some way.

What I'm trying to do is write a file to a directory. However, the 
directory

may not exist the first time I try to write a file there, so I'm going to
first try to write the file, and if I get an exception, create the 
directory
(er, *try* to), and *then* write the file there. Here's my first shot at 
the

code:

 try:
 self.save_file(picfile_fullpath, picdata)
 except IOError as err:
 # directory doesn't exist. Try to create it.
 try:
 os.makedirs(picfile_fullpath)
 except OSError as oserr:
 logging.error("Can't create file path: %s (%s)" %
(picfile_fullpath, oserr))
 else:
 # Created dir, now write file.
 try:
 self.save_file(picfile_fullpath, picdata)
 except IOError as err:
 logging.error("Bailing. Couldn't save file %s (%s)" 
%

(picfile_fullpath, err))
 return False


Unless this is in a tight loop, I think I'd write:

try:
os.makedirs(picfile_fullpath)
try:
self.save_file(picfile_fullpath, picdata)
return True
# all/only error handling code follows.
except IOError as err:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

return False
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % (picfile_fullpath, 
oserr))

return False

which eliminates the duplicated save_file step.



Doesn't this seem less readable than the 'ask permission' equivalent? I
think it does, but in this case asking permission for every single 
operation

when the dir will only need to be created a single time (and then may be
written to several hundred times) is pretty wasteful.


Agreed -- if it's in a loop, you'd want to only check once.  Of course, if 
the directory is eg an nfs share, continued access could be an issue.


HTH,

Emile




I suppose I could set some sentinel variable and check for it in a while
loop, but then I need some other scaffolding code to make sure I don't
infinitely loop trying to create the directory, and probably some other
stuff I'm forgetting, so it strikes me as being just as messy.

Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian






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



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


___
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-13 Thread Roelof Wobben




> Date: Mon, 13 Sep 2010 15:31:08 -0400
> Subject: Re: [Tutor] FW: wierd replace problem
> From: joel.goldst...@gmail.com
> To: rwob...@hotmail.com
>
>
>
> On Mon, Sep 13, 2010 at 2:24 PM, Roelof Wobben
>> wrote:
>
>
>
> 
>> From: rwob...@hotmail.com
>> To: joel.goldst...@gmail.com
>> Subject: RE: [Tutor] wierd replace problem
>> Date: Mon, 13 Sep 2010 18:23:36 +
>>
>>
>>
>>
>> 
>>> Date: Mon, 13 Sep 2010 14:18:36 -0400
>>> From: joel.goldst...@gmail.com
>>> To: tutor@python.org
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>>
>>>
>>> On Mon, Sep 13, 2010 at 2:08 PM, bob gailer
 wrote:
>>> On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>>>
>>> [snip]
>>>
>>> hello Alan,
>>>
>>> Your right. Then it prints like this "'tis
>>> Which is not right. It must be tis.
>>> So the replace does not what it supposed to do.
>>>
>>> Sorry but I am now more confused. After discovering no \ in the text
>>> file now you seem to have have a new specification, which is to get rid
>>> of the '.
>>>
>>> I suggest you give a clear, complete and correct problem statement.
>>> Right now we are shooting in the dark at a moving target.
>>>
>>> Something like.
>>>
>>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>>
>>> Remove these characters ...
>>>
>>> Split into words (not letters?) where word is defined as
>>>
>>> Count the frequency of each word.
>>>
>>>
>>> --
>>> Bob Gailer
>>> 919-636-4239
>>> Chapel Hill NC
>>>
>>> ___
>>> Tutor maillist - Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>> How about using str.split() to put words in a list, then run strip()
>>> over each word with the required characters to be removed ('`")
>>>
>>> --
>>> Joel Goldstick
>>>
>>>
>>> ___ Tutor maillist -
>>> Tutor@python.org To unsubscribe or change
> subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Hello Joel.
>
> That can be a solution but when i have --dark the -- must be removed.
> But in a-piece the - must not be removed.
>
> Roelof
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> strip only removes from start and end of string. Not from the middle,
> so a-piece would stay as a word
>
> --
> Joel Goldstick
>
 
Oke, 
 
I have tried that but then I see this message :
 
 File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 8
letter2 = letter.strip('`")
  ^
SyntaxError: EOL while scanning string literal
 
Change it to (''`"") do not help either.
 
Roelof

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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Adam Bark

On 13/09/10 20:12, Brian Jones wrote:
Thanks for the replies so far. One thing that's probably relevant: 
once a directory is created, I can expect to write a couple of hundred 
files to it, so doing a 'try os.makedirs' right off the bat strikes me 
as coding for the *least* common case instead of the *most* common 
(which is that the directory exists and the file write succeeds). If 
this were a one-off file write well then things get easier, but 
I'd like to avoid attempting a makedirs 100 times when 99 of those 
times I know it'll give me an error.


brian

On Mon, Sep 13, 2010 at 3:07 PM, Evert Rol > wrote:


> I've been coding Python long enough that 'asking forgiveness
instead of permission' is my first instinct, but the resulting
code is sometimes clumsy, and I wonder if someone can suggest
something I'm missing, or at least validate what's going on here
in some way.
>
> What I'm trying to do is write a file to a directory. However,
the directory may not exist the first time I try to write a file
there, so I'm going to first try to write the file, and if I get
an exception, create the directory (er, *try* to), and *then*
write the file there.

That would work.
Though I would just try to create the error directory first. If
that fails, I check the error message/code in the except clause:
if it indicates the directory already exists, I pass the
exception, otherwise reraise it.
Then I continue with creating the file within the directory I now
am certain of exists.
Note 1: certain is only half: some other process could remove the
directory in the split second between my code creating it and my
code creating the file. If you think that could happen, you'll
need to look at the other ways to do this.
Note 2: the directory can exist, but not have write access to your
process. So between the try-except for creating a directory and
the try-except for creating a file, you may put in a try-except
for chmod. Of course, if you're not the owner, both the chmod and
file creation will fail (I'm assuming some *nix platform here, btw).

> Here's my first shot at the code:
>
> try:
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> # directory doesn't exist. Try to create it.

Careful: you're not checking the actually error given by the
exception. There may be more than one reason that the file can't
be created (examples: the permissions mentioned above, or some
file creation limit in a directory).


> try:
> os.makedirs(picfile_fullpath)
> except OSError as oserr:
> logging.error("Can't create file path: %s (%s)"
% (picfile_fullpath, oserr))
> else:
> # Created dir, now write file.
> try:
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> logging.error("Bailing. Couldn't save file
%s (%s)" % (picfile_fullpath, err))
> return False
>
> Doesn't this seem less readable than the 'ask permission'
equivalent? I think it does, but in this case asking permission
for every single operation when the dir will only need to be
created a single time (and then may be written to several hundred
times) is pretty wasteful.

One of the things I once read (but I forgot where) on this issue,
is the usual "it depends". It depends whether you except that
often, the directory doesn't exist and the file can't directly be
created. In that case, if may be quicker to ask permission first
(simple if-statement). If you expect that in general, you can
immediately create the file within the directory (so an exception
is unlikely to occur), then use a try-except clause.
But don't take my word for it; I'd be curious what others on this
list say about this.


>
> I suppose I could set some sentinel variable and check for it in
a while loop, but then I need some other scaffolding code to make
sure I don't infinitely loop trying to create the directory, and
probably some other stuff I'm forgetting, so it strikes me as
being just as messy.
>
> Is there a clean sort of pattern to apply in instances like this?

I guess not, though readability of code is an important thing to
consider. In this case, I don't find the correctly unreadable, but
at some point, these things do tend to get out of hand and you're
better off coding it differently (perhaps even using functions).


 Evert

Well surely then you just check the directory first with a try: 
os.makedirs. Then your try: self.savefile for each file.


___
Tutor maillist  -  T

[Tutor] input problem

2010-09-13 Thread ANKUR AGGARWAL
Suppose i am taking input or various variables like
a=raw_input("...") //hello
b=raw_input("")//hi
c=raw_input("...")//hello
d=raw_input("..")//hello
but i want to run a common function when input is hello

so instead of
if a=="hello":
 fun()
then again for b and then again for c then d and so on i have to apply the
code for the specific variable ,
i want to run the function whenever in the code input is "hello"
i am wondering is there is any way like
if input=="hello":
 fun()
i hope you get my point.. Help me out please
Thanks in advance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input problem

2010-09-13 Thread christopher . henk
ANKUR AGGARWAL wrote on 09/13/2010 04:45:41 PM:

> Suppose i am taking input or various variables like
> a=raw_input("...") //hello
> b=raw_input("")//hi
> c=raw_input("...")//hello
> d=raw_input("..")//hello
> but i want to run a common function when input is hello
> 
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply 
the code for the specific variable , 
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please

You put your inputs into a list and see if "hello" is in the list.
 
inputlist=[a,b,c,d]
if "hello" in inputlist:
fun()

or if you want to run fun() once for every "hello" you can then loop over 
the list.

inputlist=[a,b,c,d]
for inputitem in inputlist: 
if "hello" == inputitem:
fun()

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


Re: [Tutor] input problem

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 6:45 AM, ANKUR AGGARWAL  wrote:
> Suppose i am taking input or various variables like
> a=raw_input("...") //hello
> b=raw_input("")//hi
> c=raw_input("...")//hello
> d=raw_input("..")//hello
> but i want to run a common function when input is hello
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply the
> code for the specific variable ,
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please
> Thanks in advance

How about this design pattern:

def hello():
   print "Hello World!"

prompt = "..."
s = raw_input(prompt)
while s:
   if s == "hello":
  hello()
   elif s == "quit":
  break
   s = raw_input(prompt)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
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-13 Thread bob gailer

 On 9/13/2010 2:21 PM, Roelof Wobben wrote:






From: rwob...@hotmail.com
To: bgai...@gmail.com
Subject: RE: [Tutor] wierd replace problem
Date: Mon, 13 Sep 2010 18:19:43 +

I suggest you give a clear, complete and correct problem statement.
Right now we are shooting in the dark at a moving target.

Something like.

Given the file alice_in_wonderland.txt, copied from url so-and-so

Remove these characters ...

Split into words (not letters?) where word is defined as

Count the frequency of each word. =

Hello,

The problem as stated in the book is :


3.Write a program called alice_words.py that creates a text file named 
alice_words.txt containing an alphabetical listing of all the words found in 
alice_in_wonderland.txt together with the number of times each word occurs. The 
first 10 lines of your output file should look something like this:
Word Count
===
a 631
a-piece 1
abide 1
able 1
about 94
above 3
absence 1
absurd 2
How many times does the word, alice, occur in the book?


We still do not have a definition of "word". Only some examples.


The text can be found here : 
http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt

So I open the file.
Read the first rule.

This is no problem for me.

Then I want to remove some characters like ' , " when the word in the text 
begins with these characters.
And there is the problem. The ' and " can't be removed with replace.


Not true. replace() will replace any character. You wrote in your other post


 letter2 = letter.strip('`")



 SyntaxError: EOL while scanning string literal



 Change it to (''`"") do not help either.


Do you understand the error? strip expects a string.
'`" and ''`"" are NOT strings. Please review Python syntax for string literals.
Here again we bump into a fundamental problem - your not understanding some of 
the basics of Python.


So in the output you will see something like this "dark instead of dark

word is the words of the sentence which is read in from the text-file.

Am i now clear what the problem is Im facing.
Somewhat clearer. We need a definition of "word". Examples help but are 
not definitions.


Example - word is a string of characters including a-z and -. The first 
and last characters must be in a-z. Your definition may be different.


BTW see http://dictionary.reference.com/browse/%27tis where 'tis IS a word.

Your original program (what DID become of the backslash???) is WAY off 
the mark. You must process one character at a time, decide whether it is 
the beginning of a word, the end of a word, within a word, or outside 
any word.


Take the beginning of the alice file, and BY HAND decide which category 
the first character is in. Then the 2nd. etc. That gives you the 
algorithm, Then translate that to Python.


Keep fishing. One day the struggle will be over.

HTH

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Steven D'Aprano
On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:

> How about using str.split() to put words in a list, then run strip()
> over each word with the required characters to be removed ('`")


Doesn't work. strip() only removes characters at the beginning and end 
of the word, not in the middle:


>>> "'I can't do this'".strip("'")
"I can't do this"

If the aim is to remove all quotation marks, replace() is the right way 
to go about it. It's not that hard either.

text = text.replace("'", "").replace('"', "").replace("`", "")

will remove all "standard" quotation marks, although if the source text 
contains non-English or unusual unicode quotes, you will need to do 
more work.

Or if you prefer something more easily extendable to other characters:

for c in "\"'`":
text = text.replace(c, "")



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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Joel Goldstick
On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano wrote:

> On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
>
> > How about using str.split() to put words in a list, then run strip()
> > over each word with the required characters to be removed ('`")
>
>
> Doesn't work. strip() only removes characters at the beginning and end
> of the word, not in the middle:
>


Exactly, you first split the words into a list of words, then strip each
word



> >>> "'I can't do this'".strip("'")
> "I can't do this"
>
> If the aim is to remove all quotation marks, replace() is the right way
> to go about it. It's not that hard either.
>
> text = text.replace("'", "").replace('"', "").replace("`", "")
>
> will remove all "standard" quotation marks, although if the source text
> contains non-English or unusual unicode quotes, you will need to do
> more work.
>
> Or if you prefer something more easily extendable to other characters:
>
> for c in "\"'`":
>text = text.replace(c, "")
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
___
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-13 Thread Steven D'Aprano
On Tue, 14 Sep 2010 08:05:33 am bob gailer wrote:

> > 3.Write a program called alice_words.py that creates a text file
> > named alice_words.txt containing an alphabetical listing of all the
> > words found in alice_in_wonderland.txt together with the number of
> > times each word occurs. The first 10 lines of your output file
> > should look something like this: Word Count
> > ===
> > a 631
> > a-piece 1
> > abide 1
> > able 1
> > about 94
> > above 3
> > absence 1
> > absurd 2
> > How many times does the word, alice, occur in the book?
>
> We still do not have a definition of "word". Only some examples.

Nor do we have a definition of "text", "file", "alphabetical", "first", 
"10", "lines", "definition", or "overly pedantic".

A reasonable person would use the common meaning of all of these words, 
unless otherwise told differently. In this case, the only ambiguity is 
whether hyphenated words like "a-piece" should count as two words or 
one, but fortunately the example above clearly shows that it should 
count as a single word.

This is an exercise, not a RFC. Be reasonable.


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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Steven D'Aprano
On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:
> On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano 
wrote:
> > On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
> > > How about using str.split() to put words in a list, then run
> > > strip() over each word with the required characters to be removed
> > > ('`")
> >
> > Doesn't work. strip() only removes characters at the beginning and
> > end of the word, not in the middle:
>
> Exactly, you first split the words into a list of words, then strip
> each word

Of course, if you don't want to remove ALL punctuation marks, but only 
those at the beginning and end of words, then strip() is a reasonable 
approach. But if the aim is to strip out all punctuation, no matter 
where, then it can't work.

Since the aim is to count words, a better approach might be a hybrid -- 
remove all punctuation marks like commas, fullstops, etc. no matter 
where they appear, keep internal apostrophes so that words like "can't" 
are different from "cant", but remove external ones. Although that 
loses information in the case of (e.g.) dialect speech:

"'e said 'e were going to kill the lady, Mister Holmes!" 
cried the lad excitedly.

You probably want to count the word as 'e rather than just e.

And hyphenation is tricky to. A lone hyphen - like these - should be 
deleted. But double-dashes--like these--are word separators, so need to 
be replaced by a space. Otherwise, single hyphens should be kept. If a 
word begins or ends with a hyphen, it should be be joined up with the 
previous or next word. But then it gets more complicated, because you 
don't know whether to keep the hyphen after joining or not.

E.g. if the line ends with: 

blah blah blah blah some-
thing blah blah blah.

should the joined up word become the compound word "some-thing" or the 
regular word "something"? In general, there's no way to be sure, 
although you can make a good guess by looking it up in a dictionary and 
assuming that regular words should be preferred to compound words. But 
that will fail if the word has changed over time, such as "cooperate", 
which until very recently used to be written "co-operate", and before 
that as "coöperate".



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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Steven D'Aprano
On Tue, 14 Sep 2010 05:07:03 am Evert Rol wrote:
> Note 2: the directory can exist, but not have write access to your
> process. So between the try-except for creating a directory and the
> try-except for creating a file, you may put in a try-except for
> chmod.

If some application tried changing permissions I had set on a directory 
or file without my direct say-so, I would dump that application 
immediately.



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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Steven D'Aprano
On Tue, 14 Sep 2010 04:31:00 am Brian Jones wrote:
> I've been coding Python long enough that 'asking forgiveness instead
> of permission' is my first instinct, but the resulting code is
> sometimes clumsy, and I wonder if someone can suggest something I'm
> missing, or at least validate what's going on here in some way.
>
> What I'm trying to do is write a file to a directory. However, the
> directory may not exist the first time I try to write a file there,
> so I'm going to first try to write the file, and if I get an
> exception, create the directory (er, *try* to), and *then* write the
> file there. Here's my first shot at the code:

Obviously this needs to go into an independent function or method for 
ease of testing, and so that you don't have to repeat yourself each 
time you write to a file.


> try:
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:

Since you don't use err, there's no need for it. But since you have it, 
you might as well use it, and inspect the error code. E.g. if the error 
is permission denied, then you can bail immediately because nothing 
else will succeed either. (Well, technically it could succeed if the 
permissions change between the first failure and the subsequent attempt 
to create the directories, but you probably don't care about that.)


> # directory doesn't exist. Try to create it.
> try:
> os.makedirs(picfile_fullpath)
> except OSError as oserr:
> logging.error("Can't create file path: %s (%s)" %
> (picfile_fullpath, oserr))
> else:
> # Created dir, now write file.
> try:
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> logging.error("Bailing. Couldn't save file %s
> (%s)" % (picfile_fullpath, err))
> return False
>
> Doesn't this seem less readable than the 'ask permission' equivalent?

Yes, but that's because the "ask permission" equivalent is fatally 
flawed -- permission can be revoked at any time, including a 
microsecond after you've been told "Yes" but before you actually get to 
save the file.

You've got more or less the right approach here, although you can 
streamline it so you're only trying to write the file once rather than 
twice. Put this in a utility function or method, where all the 
complication is hidden, just as os.makedirs hides a lot of complexity.



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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Steven D'Aprano
On Tue, 14 Sep 2010 05:12:12 am Brian Jones wrote:
> Thanks for the replies so far. One thing that's probably relevant:
> once a directory is created, I can expect to write a couple of
> hundred files to it, so doing a 'try os.makedirs' right off the bat
> strikes me as coding for the *least* common case instead of the
> *most* common (which is that the directory exists and the file write
> succeeds). If this were a one-off file write well then things get
> easier, but I'd like to avoid attempting a makedirs 100 times when 99
> of those times I know it'll give me an error.

Why? Do you know how much time it will save? The extra scaffolding code, 
setting up the try...except block, takes time too. Unless you've 
profiled the code, you have no idea how wasteful 100 calls to makedirs 
will be, compared to the alternatives of:

look to see if the directory exists 100 times

or 

setting up 100 extra try...except blocks.

In any case, the time it takes to call makedirs() unnecessarily will 
probably be so small compared to the time you actually spending writing 
data to disk that you won't notice -- who cares if you reduce the time 
to save 100 files from 1.302 seconds to 1.293 seconds? But don't 
believe me, because I'm only guessing. Write both versions and time 
them with *realistic* amounts of data. If you normally write 100 five 
gigabyte files over a network share, why are we even having this 
conversation??? *wink*

Write for the reader (that would be you, in six months time) first, and 
then only optimize when you have to.


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


[Tutor] How to numerically sort strings that start with numbers?

2010-09-13 Thread Pete O'Connell
theList = ["21 trewuuioi","3zxc","134445"]
print sorted(theList)

Hi, the result of the sorted list above doesn't print in the order I
want. Is there a straight forward way of getting python to print
['3zxc','21 trewuuioi','134445']
rather than ['134445', '21 trewuuioi', '3zxc']?

Any help would be greatly appreciated
Pete
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to numerically sort strings that start with numbers?

2010-09-13 Thread Adam Bark

On 14/09/10 01:11, Pete O'Connell wrote:

theList = ["21 trewuuioi","3zxc","134445"]
print sorted(theList)

Hi, the result of the sorted list above doesn't print in the order I
want. Is there a straight forward way of getting python to print
['3zxc','21 trewuuioi','134445']
rather than ['134445', '21 trewuuioi', '3zxc']?

Any help would be greatly appreciated
Pete
   

print sorted(theList)[::-1]

as list indices go [start:end:step] what this means is the whole list 
starting from the end and working backwards.
You can also have a look at reversed() if you want an iterator or you 
can use theList.reverse() if you want to reverse in place ie.


>>> l = ["21 trewuuioi","3zxc","134445"]
>>> l.reverse()
>>> print l
['134445', '3zxc', '21 trewuuioi']


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


Re: [Tutor] How to numerically sort strings that start with numbers?

2010-09-13 Thread David Hutto
On Mon, Sep 13, 2010 at 9:11 PM, Adam Bark  wrote:
> On 14/09/10 01:11, Pete O'Connell wrote:
>>
>> theList = ["21 trewuuioi","3zxc","134445"]
>> print sorted(theList)
>>
>> Hi, the result of the sorted list above doesn't print in the order I
>> want. Is there a straight forward way of getting python to print
>> ['3zxc','21 trewuuioi','134445']
>> rather than ['134445', '21 trewuuioi', '3zxc']?
>>
>> Any help would be greatly appreciated
>> Pete
>>
>
> print sorted(theList)[::-1]
>
> as list indices go [start:end:step] what this means is the whole list
> starting from the end and working backwards.
> You can also have a look at reversed() if you want an iterator or you can
> use theList.reverse() if you want to reverse in place ie.
>
 l = ["21 trewuuioi","3zxc","134445"]
 l.reverse()
 print l
> ['134445', '3zxc', '21 trewuuioi']
>
>
> HTH
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Thanks from me too, because I kept getting None when trying
to directly print theList.reverse()

>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> theList.reverse()
>>> print theList
['134445', '3zxc', '21 trewuuioi']
>>> print theList.reverse()
None
>>> print type(theList.reverse())

>>> print type(theList)

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


Re: [Tutor] How to numerically sort strings that start with numbers?

2010-09-13 Thread Adam Bark

On 14/09/10 02:24, Pete O'Connell wrote:

Hi I don't actaully need the list printed reversed, I need it printed
from smallest number to largest

   

Just sorting gives you the list from smallest to largest.

For example:
#

theList = ["21 trewuuioi","374zxc","13447"]
print sorted(theList)
   

['13447', '21 trewuuioi', '374zxc']
 

#the rabove result is not what I want


If I reverse that I still don't get the items in numerical order. The
result I want is:
   

['21 trewuuioi','374zxc','13447']
 

Before you said you wanted it like this:  ['3zxc','21 trewuuioi','134445']

The order above isn't in any obvious numerical order.
Anyway I think I see where you are coming from. In my previous example I 
forgot to assign the sorted list back to theList. Hopefully the 
following will make this clear.


>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> sorted(theList)
['134445', '21 trewuuioi', '3zxc']
>>> theList
['21 trewuuioi', '3zxc', '134445']
>>> theList = sorted(theList)
>>> theList
['134445', '21 trewuuioi', '3zxc']
>>> theList[::-1]
['3zxc', '21 trewuuioi', '134445']
>>> theList.reverse()
>>> theList
['3zxc', '21 trewuuioi', '134445']

as you can see sorted makes a new list rather than modifying your original.

On Tue, Sep 14, 2010 at 10:41 AM, Adam Bark  wrote:
   

On 14/09/10 01:11, Pete O'Connell wrote:
 

theList = ["21 trewuuioi","3zxc","134445"]
print sorted(theList)

Hi, the result of the sorted list above doesn't print in the order I
want. Is there a straight forward way of getting python to print
['3zxc','21 trewuuioi','134445']
rather than ['134445', '21 trewuuioi', '3zxc']?

Any help would be greatly appreciated
Pete

   

print sorted(theList)[::-1]

as list indices go [start:end:step] what this means is the whole list
starting from the end and working backwards.
You can also have a look at reversed() if you want an iterator or you can
use theList.reverse() if you want to reverse in place ie.

 

l = ["21 trewuuioi","3zxc","134445"]
l.reverse()
print l
   

['134445', '3zxc', '21 trewuuioi']


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

 



   


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


[Tutor] If/elif/else when a list is empty

2010-09-13 Thread aeneas24

Hi,

I'm parsing IMDB movie reviews (each movie is in its own text file). In my 
script, I'm trying to extract genre information. Movies have up to three 
categories of genres--but not all have a "genre" tag and that fact is making my 
script abort whenever it encounters a movie text file that doesn't have a 
"genre" tag. 

I thought the following should solve it, but it doesn't. The basic question is 
how I say "if genre information doesn't at all, just make rg1=rg2=rg3="NA"?

rgenre = re.split(r';', rf.info["genre"]) # When movies have genre information 
they store it as Drama;Western;Thriller

if len(rgenre)>0:
  if len(rgenre)>2:
  rg1=rgenre[0]
  rg2=rgenre[1]
  rg3=rgenre[2]
  elif len(rgenre)==2:
  rg1=rgenre[0]
  rg2=rgenre[1]
  rg3="NA"
  elif len(rgenre)==1:
  rg1=rgenre[0]
  rg2="NA"
  rg3="NA"
   else len(rgenre)<1: # I was hoping this would take care of the "there is no 
genre information" scenario but it doesn't
   rg1=rg2=rg3="NA"

This probably does a weird nesting thing, but even simpler version I have tried 
don't work. 

Thanks very much for any help!

Tyler
  



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


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread Vince Spicer
On Mon, Sep 13, 2010 at 9:58 PM,  wrote:

>  Hi,
>
> I'm parsing IMDB movie reviews (each movie is in its own text file). In my
> script, I'm trying to extract genre information. Movies have up to three
> categories of genres--but not all have a "genre" tag and that fact is making
> my script abort whenever it encounters a movie text file that doesn't have a
> "genre" tag.
>
> I thought the following should solve it, but it doesn't. The basic question
> is how I say "if genre information doesn't at all, just make
> rg1=rg2=rg3="NA"?
>
> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre
> information they store it as Drama;Western;Thriller
>
> if len(rgenre)>0:
>   if len(rgenre)>2:
>   rg1=rgenre[0]
>   rg2=rgenre[1]
>   rg3=rgenre[2]
>   elif len(rgenre)==2:
>   rg1=rgenre[0]
>   rg2=rgenre[1]
>   rg3="NA"
>   elif len(rgenre)==1:
>   rg1=rgenre[0]
>   rg2="NA"
>   rg3="NA"
>else len(rgenre)<1: # I was hoping this would take care of the "there is
> no genre information" scenario but it doesn't
>rg1=rg2=rg3="NA"
>
> This probably does a weird nesting thing, but even simpler version I have
> tried don't work.
>
> Thanks very much for any help!
>
> Tyler
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Hey Tyler you can simplify this with a onliner.

rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))

Hope that helps, if you have any questions feel free to ask.

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


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 1:58 PM,   wrote:
> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre

First question. Why are you not using an XML parser (it looks like
your IMDB data files _are_ XML). e.g: elementree (in the standard
library).

>    else len(rgenre)<1: # I was hoping this would take care of the "there is
> no genre information" scenario but it doesn't
>    rg1=rg2=rg3="NA"

the "else" statement does not expect (nor accept) an expression after
it, just write:

else:
   ...

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread aeneas24

Hi Vince,

Thanks very much for the one-line version--unfortunately, I still get errors. 
The overall script runs over every text file in a directory, but as soon as it 
hits a text file without a  tag, it gives this error:

Traceback (most recent call last):
  File 
"C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 
168, in 
main(".","output.csv")
  File 
"C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 
166, in main
os.path.walk(top_level_dir, reviewDirectory, writer )
  File "C:\Python26\lib\ntpath.py", line 259, in walk
func(arg, top, names)
  File 
"C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 
162, in reviewDirectory
reviewFile( dirname+'/'+fileName, args )
  File 
"C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 
74, in reviewFile
rgenre = re.split(r';', rf.info["genre"])
KeyError: 'genre'

I'm about to give what may be too much information--I really thought there must 
be a way to say "don't choke if you don't find any rgenres because 
rf.info["genre"] was empty". But maybe I need to define the "None" condition 
earlier?

Basically a text file has this structure:

High Noon
Drama;Western # But this tag doesn't exist for all text files
# etc


u493498
9 out of 10
A great flick
blah blah blah
# etc

# next review--all about the movie featured in the info tags






-Original Message-
From: Vince Spicer 
To: aenea...@priest.com
Cc: tutor@python.org
Sent: Mon, Sep 13, 2010 9:08 pm
Subject: Re: [Tutor] If/elif/else when a list is empty





On Mon, Sep 13, 2010 at 9:58 PM,  wrote:

Hi,
 
I'm parsing IMDB movie reviews (each movie is in its own text file). In my 
script, I'm trying to extract genre information. Movies have up to three 
categories of genres--but not all have a "genre" tag and that fact is making my 
script abort whenever it encounters a movie text file that doesn't have a 
"genre" tag. 
 
I thought the following should solve it, but it doesn't. The basic question is 
how I say "if genre information doesn't at all, just make rg1=rg2=rg3="NA"?
 
rgenre = re.split(r';', rf.info["genre"]) # When movies have genre information 
they store it as Drama;Western;Thriller
 
if len(rgenre)>0:
  if len(rgenre)>2:
  rg1=rgenre[0]
  rg2=rgenre[1]
  rg3=rgenre[2]
  elif len(rgenre)==2:
  rg1=rgenre[0]
  rg2=rgenre[1]
  rg3="NA"
  elif len(rgenre)==1:
  rg1=rgenre[0]
  rg2="NA"
  rg3="NA"
   else len(rgenre)<1: # I was hoping this would take care of the "there is no 
genre information" scenario but it doesn't
   rg1=rg2=rg3="NA"
 
This probably does a weird nesting thing, but even simpler version I have tried 
don't work. 
 
Thanks very much for any help!
 
Tyler
  




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




Hey Tyler you can simplify this with a onliner.


rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))


Hope that helps, if you have any questions feel free to ask.


Vince

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


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread Vince Spicer
Tyler,

This is a simple error the KeyError is caused because the key isn't in the
dictionary
http://docs.python.org/library/exceptions.html#exceptions.KeyError and easy
fix you can either check for the key prior to using or use the get method

1) rgenre = re.split(r';', rf.info["genre"]) if "genre" in rf.info else []
the regex will never get executed here and an empty list will be returned if
genre not present

2) rgenre = re.split(r';', rf.info.get("genre", ''))
the get will not throw this error and return '' if ''genre' is not found in
the dictionary

Hope that helps,

Vince


On Mon, Sep 13, 2010 at 10:46 PM,  wrote:

> Hi Vince,
>
> Thanks very much for the one-line version--unfortunately, I still get
> errors. The overall script runs over every text file in a directory, but as
> soon as it hits a text file without a  tag, it gives this error:
>
> Traceback (most recent call last):
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 168, in 
> main(".","output.csv")
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 166, in main
> os.path.walk(top_level_dir, reviewDirectory, writer )
>   File "C:\Python26\lib\ntpath.py", line 259, in walk
> func(arg, top, names)
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 162, in reviewDirectory
> reviewFile( dirname+'/'+fileName, args )
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 74, in reviewFile
>
> rgenre = re.split(r';', rf.info["genre"])
> KeyError: 'genre'
>  I'm about to give what may be too much information--I really thought
> there must be a way to say "don't choke if you don't find any rgenres
> because rf.info["genre"] was empty". But maybe I need to define the "None"
> condition earlier?
>
> Basically a text file has this structure:
> 
> High Noon
> Drama;Western # But this tag doesn't exist for all text
> files
> # etc
> 
> 
> u493498
> 9 out of 10
> A great flick
> blah blah blah
> # etc
> 
> # next review--all about the movie featured in the info tags
>
>
>
>
> -Original Message-
> From: Vince Spicer 
> To: aenea...@priest.com
> Cc: tutor@python.org
> Sent: Mon, Sep 13, 2010 9:08 pm
> Subject: Re: [Tutor] If/elif/else when a list is empty
>
>
>
> On Mon, Sep 13, 2010 at 9:58 PM,  wrote:
>
>> Hi,
>>
>> I'm parsing IMDB movie reviews (each movie is in its own text file). In my
>> script, I'm trying to extract genre information. Movies have up to three
>> categories of genres--but not all have a "genre" tag and that fact is making
>> my script abort whenever it encounters a movie text file that doesn't have a
>> "genre" tag.
>>
>> I thought the following should solve it, but it doesn't. The basic
>> question is how I say "if genre information doesn't at all, just make
>> rg1=rg2=rg3="NA"?
>>
>> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre
>> information they store it as Drama;Western;Thriller
>>
>> if len(rgenre)>0:
>>   if len(rgenre)>2:
>>   rg1=rgenre[0]
>>   rg2=rgenre[1]
>>   rg3=rgenre[2]
>>   elif len(rgenre)==2:
>>   rg1=rgenre[0]
>>   rg2=rgenre[1]
>>   rg3="NA"
>>   elif len(rgenre)==1:
>>   rg1=rgenre[0]
>>   rg2="NA"
>>   rg3="NA"
>>else len(rgenre)<1: # I was hoping this would take care of the "there
>> is no genre information" scenario but it doesn't
>>rg1=rg2=rg3="NA"
>>
>> This probably does a weird nesting thing, but even simpler version I have
>> tried don't work.
>>
>> Thanks very much for any help!
>>
>> Tyler
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> Hey Tyler you can simplify this with a onliner.
>
>  rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))
>
>  Hope that helps, if you have any questions feel free to ask.
>
>  Vince
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread James Mills
On Tue, Sep 14, 2010 at 2:46 PM,   wrote:
>    rgenre = re.split(r';', rf.info["genre"])
> KeyError: 'genre'

Use something like this:

if "genre" in rf.info:
   rgenre = re.split(..., ...)
else:
   # ... no genre

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor