[Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dick Moores
I've taken a long break from Python, and now I want to try scripting
with 2.62. I downloaded and installed 2.62, changed Win XP
environmental variables to use Python26. Entering python at the
command line shows I'm using 2.62:

C:\Documents and Settings\Riley>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

So I'm able to try out the new features of 2.6 (I had been using
2.51), but I can't get IDLE to use 2.6. When I click on
E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

And of course, the new 2.6 features don't work.

Advice, please.

Thanks,

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


Re: [Tutor] simple text replace

2009-07-27 Thread Albert-Jan Roskam

Hi!

Did you consider using a regex?

import re
re.sub("python\s", "snake ", "python is cool, pythonprogramming...")

Cheers!!
Albert-Jan


--- On Mon, 7/27/09, Dave Angel  wrote:

> From: Dave Angel 
> Subject: Re: [Tutor] simple text replace
> To: "j booth" 
> Cc: tutor@python.org
> Date: Monday, July 27, 2009, 12:41 AM
> j booth wrote:
> > Hello,
> > 
> > I am scanning a text file and replacing words with
> alternatives. My
> > difficulty is that all occurrences are replaced (even
> if they are part of
> > another word!)..
> > 
> > This is an example of what I have been using:
> > 
> >     for line in
> fileinput.FileInput("test_file.txt",inplace=1):
> >   
> >>         line =
> line.replace(original, new)
> >>         print line,
> >>     
>    fileinput.close()
> >>     
> > 
> > 
> > original and new are variables that have string values
> from functions..
> > original finds each word in a text file and old is a
> manipulated
> > replacement. Essentially, I would like to replace only
> the occurrence that
> > is currently selected-- not the rest. for example:
> > 
> > python is great, but my python knowledge is limited!
> regardless, I enjoy
> >   
> >> pythonprogramming
> >>     
> > 
> > 
> > returns something like:
> > 
> > snake is great, but my snake knowledge is limited!
> regardless, I enjoy
> >   
> >> snakeprogramming
> >>     
> > 
> > 
> > thanks so much!
> > 
> >   
> Not sure what you mean by "currently selected," you're
> processing a line at a time, and there are multiple
> legitimate occurrences of the word in the line.
> 
> The trick is to define what you mean by "word." 
> replace() has no such notion.  So we want to write a
> function such as:
> 
> given three strings, line, inword, and outword.  Find
> all occurrences of inword in the line, and replace all of
> them with outword.  The definition of word is a group
> of alphabetic characters (a-z perhaps) that is surrounded by
> non-alphabetic characters.
> 
> The approach that I'd use is to prepare a translated copy
> of the line as follows:   Replace each
> non-alphabetic character with a space.  Also insert a
> space at the beginning and one at the end.  Now, take
> the inword, and similarly add spaces at begin and end. 
> Now search this modified line for all occurrences of this
> modified inword, and make a list of the indices where it is
> found.  In your example line, there would be 2 items in
> the list.
> 
> Now, using the original line, use that list of indices to
> substitute the outword in the appropriate places.  Use
> slices to do it, preferably from right to left, so the
> indices will work even though the string is changing. 
> (The easiest way to do right to left is to reverse() the
> list.
> 
> DaveA
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread davidwilson
Here is what I have so far:

import os
import csv

countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])
print len(files)

for file in files:
file = file.strip('.svg')
print file
#if countries.has_key(file):
#   print file

When I run this I get:

Flag_of_Uganda
Flag_of_the_United_State
Flag_of_Abkhazia
Flag_of_Montenegro
Flag_of_Qatar
Flag_of_Gabon
Flag_of_Uzbekistan
Flag_of_Kiribati
Flag_of_Armenia
Flag_of_Panama
Flag_of_Monaco
Flag_of_Australia
Flag_of_Liechtenstein
Flag_of_Tunisia
Flag_of_Georgia
Flag_of_Palau
Flag_of_the_Central_African_Republic
...

The problem is that for example the file Flag_of_the_United_States.svg when I 
use the strip('.svg') it is returned as Flag_of_the_United_State

Also, How do I remove 'Flag_of', 'Flag_of_the_' 

I guess after this I can compare the value with the key and map the tld?

Or is it better to use regex and then search from the list of countries? But 
how???

 Original Message 
From: Tim Golden 
Apparently from: tutor-bounces+davidwilson=safe-mail@python.org
To: 
Cc: tutor@python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Sun, 26 Jul 2009 20:41:10 +0100

> davidwil...@safe-mail.net wrote:
> > OK I am lost ;(
> > 
> > I changed the code to:
> > 
>  reader = csv.reader(open("countries.csv"),  delimiter=";")
>  for row in reader:
> > ... print row 
> > ... 
> > ['bi', 'Burundi']
> > ['km', 'Comoros']
> > ['dj', 'Djibouti']
> > ['er', 'Eritrea']
> > 
> > ...
> > 
> > Now each row is a list with two items each.
> > 
> > But when I do this:
> > 
>  dic = []
>  for row in reader:
> > ... newdic.append({row[0]: row[1]})
> > ... 
>  dic
> > []
> > 
> > I get an empty dictionary
> 
> Well, you actually get an empty list :)
> To instantiate an empty dictionary, you use curly brackets:
> 
> d = {}
> 
> To add something to a dictionary, you use:
> 
> d[] = 
> 
> Try something like this:
> 
> 
> import csv
> 
> reader = csv.reader(open("countries.csv"),  delimiter=";")
> countries = {} # note the curly brackets
> for row in reader:
>code, name = row # handy Python tuple unpacking
>countries[name] = code
> 
> 
> 
> 
> Once you're used to the idea, you can get reasonably slick
> with dictionary initialisers and generator expressions:
> 
> import csv
> 
> reader = csv.reader(open("countries.csv"),  delimiter=";")
> countries = dict ((row[1], row[0]) for row in reader)
> 
> And once you're really confident (and if you're a
> fan of one-liners) you can get away with this:
> 
> import csv
> countries = dict (
>(name, code) for \
>  (code, name) in \
>  csv.reader (open ("countries.csv"), delimiter=";")
> )
> 
> 
> BTW, I tend to open csv files with "rb" as it seems to
> avoid line-ending issues with the csv module. YMMV.
> 
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Christian Witts

davidwil...@safe-mail.net wrote:

Here is what I have so far:

import os
import csv

countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])
print len(files)

for file in files:
file = file.strip('.svg')
print file
#if countries.has_key(file):
#   print file

When I run this I get:

Flag_of_Uganda
Flag_of_the_United_State
Flag_of_Abkhazia
Flag_of_Montenegro
Flag_of_Qatar
Flag_of_Gabon
Flag_of_Uzbekistan
Flag_of_Kiribati
Flag_of_Armenia
Flag_of_Panama
Flag_of_Monaco
Flag_of_Australia
Flag_of_Liechtenstein
Flag_of_Tunisia
Flag_of_Georgia
Flag_of_Palau
Flag_of_the_Central_African_Republic
...

The problem is that for example the file Flag_of_the_United_States.svg when I 
use the strip('.svg') it is returned as Flag_of_the_United_State

Also, How do I remove 'Flag_of', 'Flag_of_the_' 


I guess after this I can compare the value with the key and map the tld?

Or is it better to use regex and then search from the list of countries? But 
how???

 Original Message 
From: Tim Golden 
Apparently from: tutor-bounces+davidwilson=safe-mail@python.org
To: 
Cc: tutor@python.org

Subject: Re: [Tutor] renaming files within a directory
Date: Sun, 26 Jul 2009 20:41:10 +0100

  

davidwil...@safe-mail.net wrote:


OK I am lost ;(

I changed the code to:

  

reader = csv.reader(open("countries.csv"),  delimiter=";")
for row in reader:

... print row 
... 
['bi', 'Burundi']

['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']

...

Now each row is a list with two items each.

But when I do this:

  

dic = []
for row in reader:


... newdic.append({row[0]: row[1]})
... 
  

dic


[]

I get an empty dictionary
  

Well, you actually get an empty list :)
To instantiate an empty dictionary, you use curly brackets:

d = {}

To add something to a dictionary, you use:

d[] = 

Try something like this:


import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = {} # note the curly brackets
for row in reader:
   code, name = row # handy Python tuple unpacking
   countries[name] = code




Once you're used to the idea, you can get reasonably slick
with dictionary initialisers and generator expressions:

import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = dict ((row[1], row[0]) for row in reader)

And once you're really confident (and if you're a
fan of one-liners) you can get away with this:

import csv
countries = dict (
   (name, code) for \
 (code, name) in \
 csv.reader (open ("countries.csv"), delimiter=";")
)


BTW, I tend to open csv files with "rb" as it seems to
avoid line-ending issues with the csv module. YMMV.

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


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

  
Strip will remove those characters until it hits a character not in the 
set.  You could use file.split('.svg')[0]


--
Kind Regards,
Christian Witts


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Christian Witts

davidwil...@safe-mail.net wrote:

Here is what I have so far:

import os
import csv

countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])
print len(files)

for file in files:
file = file.strip('.svg')
print file
#if countries.has_key(file):
#   print file

When I run this I get:

Flag_of_Uganda
Flag_of_the_United_State
Flag_of_Abkhazia
Flag_of_Montenegro
Flag_of_Qatar
Flag_of_Gabon
Flag_of_Uzbekistan
Flag_of_Kiribati
Flag_of_Armenia
Flag_of_Panama
Flag_of_Monaco
Flag_of_Australia
Flag_of_Liechtenstein
Flag_of_Tunisia
Flag_of_Georgia
Flag_of_Palau
Flag_of_the_Central_African_Republic
...

The problem is that for example the file Flag_of_the_United_States.svg when I 
use the strip('.svg') it is returned as Flag_of_the_United_State

Also, How do I remove 'Flag_of', 'Flag_of_the_' 


I guess after this I can compare the value with the key and map the tld?

Or is it better to use regex and then search from the list of countries? But 
how???

 Original Message 
From: Tim Golden 
Apparently from: tutor-bounces+davidwilson=safe-mail@python.org
To: 
Cc: tutor@python.org

Subject: Re: [Tutor] renaming files within a directory
Date: Sun, 26 Jul 2009 20:41:10 +0100

  

davidwil...@safe-mail.net wrote:


OK I am lost ;(

I changed the code to:

  

reader = csv.reader(open("countries.csv"),  delimiter=";")
for row in reader:

... print row 
... 
['bi', 'Burundi']

['km', 'Comoros']
['dj', 'Djibouti']
['er', 'Eritrea']

...

Now each row is a list with two items each.

But when I do this:

  

dic = []
for row in reader:


... newdic.append({row[0]: row[1]})
... 
  

dic


[]

I get an empty dictionary
  

Well, you actually get an empty list :)
To instantiate an empty dictionary, you use curly brackets:

d = {}

To add something to a dictionary, you use:

d[] = 

Try something like this:


import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = {} # note the curly brackets
for row in reader:
   code, name = row # handy Python tuple unpacking
   countries[name] = code




Once you're used to the idea, you can get reasonably slick
with dictionary initialisers and generator expressions:

import csv

reader = csv.reader(open("countries.csv"),  delimiter=";")
countries = dict ((row[1], row[0]) for row in reader)

And once you're really confident (and if you're a
fan of one-liners) you can get away with this:

import csv
countries = dict (
   (name, code) for \
 (code, name) in \
 csv.reader (open ("countries.csv"), delimiter=";")
)


BTW, I tend to open csv files with "rb" as it seems to
avoid line-ending issues with the csv module. YMMV.

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


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

  

Hit send a little early there.
Strip will remove those characters until it hits a character not in the 
set.  You could use file.split('.svg')[0]

You could also use split to get rid of the Flag_of_ by doing
file = file.split('.svg')[0].split('_')[2]
or you could use replace for it
file = file.split('.svg')[0].replace('Flag_of_', '')

--
Kind Regards,
Christian Witts


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Tim Golden

davidwil...@safe-mail.net wrote:

Here is what I have so far:

import os
import csv

countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])


You don't really need the set () here, as I doubt your operating
system allows two files of the same name in the same directory.
Also, you can use os.listdir (".") if you want.


print len(files)

for file in files:
file = file.strip('.svg')
print file
#if countries.has_key(file):
#   print file



[... snip ...]



The problem is that for example the file Flag_of_the_United_States.svg 
when I use the strip('.svg') it is returned as Flag_of_the_United_State


Yes, this is a common gotcha when using strip. Check out the
docs of strip:

"""
Help on built-in function strip:

strip(...)
   S.strip([chars]) -> string or unicode

   Return a copy of the string S with leading and trailing
   whitespace removed.
   If chars is given and not None, remove characters in chars instead.
   If chars is unicode, S will be converted to unicode before stripping
"""

The parameter to strip -- if given -- is a string of chars,
any and all of which are stripped from the ends of the
string. It is not a *string* which is stripped in its
entirety; it is a list of characters. So here, Python is
stripping any of ".", "s", "v", "g" from the ends of your
string.

I suggest you put together a little function, eg:

def rstrip_string (look_in, look_for):
 if look_in.endswith (look_for):
   return look_in[:-len (look_for)]
 else:
   return look_in

which you can then call:

files = [rstrip_string (f, ".svg") for f in files]



Also, How do I remove 'Flag_of', 'Flag_of_the_' 


Same sort of idea.



I guess after this I can compare the value with the key and map the tld?

Or is it better to use regex and then search from the list of countries? But 
how???


regex would be possible here, but probably overkill.
You're very nearly there. Assuming the format of the
strings is consistently simple, you can take shortcuts
as above. If it's possible that one file has "flag_of"
while another has "flag-of" and another "flags-of" then
you might need to get fancier.


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Alan Gauld


 wrote

The problem is that for example the file Flag_of_the_United_States.svg 
when I use the strip('.svg') it is returned as Flag_of_the_United_State


Thats because strip removes all of the characters in the given string.

You would probably be better removing the extension using the 
os.path.splitext() function.


Also, How do I remove 'Flag_of', 'Flag_of_the_' 


You could try replacing with a null string. Do the second one first 
followed by the first if necessary, using the string.replace() method.


HTH,


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

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


Re: [Tutor] simple text replace

2009-07-27 Thread Dave Angel

Albert-Jan Roskam wrote:

Hi!

Did you consider using a regex?

import re
re.sub("python\s", "snake ", "python is cool, pythonprogramming...")

Cheers!!
Albert-Jan


--- On Mon, 7/27/09, Dave Angel  wrote:

  

From: Dave Angel 
Subject: Re: [Tutor] simple text replace
To: "j booth" 
Cc: tutor@python.org
Date: Monday, July 27, 2009, 12:41 AM
j booth wrote:


Hello,

I am scanning a text file and replacing words with
  

alternatives. My


difficulty is that all occurrences are replaced (even
  

if they are part of


another word!)..

This is an example of what I have been using:

 for line in
  

fileinput.FileInput("test_file.txt",inplace=1):

   
  

 line =


line.replace(original, new)


 print line,
 


   fileinput.close()

 


original and new are variables that have string values
  

from functions..


original finds each word in a text file and old is a
  

manipulated


replacement. Essentially, I would like to replace only
  

the occurrence that


is currently selected-- not the rest. for example:

python is great, but my python knowledge is limited!
  

regardless, I enjoy

   
  

pythonprogramming
 


returns something like:

snake is great, but my snake knowledge is limited!
  

regardless, I enjoy

   
  

snakeprogramming
 


thanks so much!

   
  

Not sure what you mean by "currently selected," you're
processing a line at a time, and there are multiple
legitimate occurrences of the word in the line.

The trick is to define what you mean by "word." 
replace() has no such notion.  So we want to write a

function such as:

given three strings, line, inword, and outword.  Find
all occurrences of inword in the line, and replace all of
them with outword.  The definition of word is a group
of alphabetic characters (a-z perhaps) that is surrounded by
non-alphabetic characters.

The approach that I'd use is to prepare a translated copy
of the line as follows:   Replace each
non-alphabetic character with a space.  Also insert a
space at the beginning and one at the end.  Now, take
the inword, and similarly add spaces at begin and end. 
Now search this modified line for all occurrences of this

modified inword, and make a list of the indices where it is
found.  In your example line, there would be 2 items in
the list.

Now, using the original line, use that list of indices to
substitute the outword in the appropriate places.  Use
slices to do it, preferably from right to left, so the
indices will work even though the string is changing. 
(The easiest way to do right to left is to reverse() the

list.

DaveA

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


(Please don't top-post on this list.  The message then appears out of 
order.  Append new responses to end, or inline when appropriate)


Yes, a regex would make a lot of sense here.  But a person should not 
take on regular expressions till they have lots of experience with the 
rest of the language.  Besides, it's pretty easy to have subtle bugs, 
even with such a simple case.  For example your re string would 
erroneously convert the word "newpython", and miss the last two 
occurrences of the real word "python" near the end of the string.


import re
print st = re.sub("python\s", "snake ", "python is cool, 
pythonprogramming... newpython becomes python, or python")


Output:  snake is cool, pythonprogramming... newsnake becomes python, or 
python


(gives the wrong answer, in three places)

DaveA

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


Re: [Tutor] First code snipet

2009-07-27 Thread Dave Angel

Darth Kaboda wrote:
Good point. It is important to state your goal for the code, preferably 
in comments in your code, as well as in the message asking us the 
question. Suggest you include a doc-string for each class and method 
declaration.


But it's important to tell us how you expect to use it, as well. If 
it's for your own learning, then it's pretty good as it is. But if you 
intend to show it to prospective employers, there are a lot of ways to 
clean it up.



So...

Unlike Java, not everything needs to be in a class. This shuffler class 
accomplishes nothing that the module doesn't already do. The only 
instance attribute you use is rgen, and that could just as readily have 
been a global (visible within the entire module).


Naming is important. I think I would have factored it into three 
functions cut() and ripple(). shuffle() simply calls cut(), then ripple().


You need to know the library better. Andreas already mentioned the std 
library random.shuffle(), and you correctly explained why you didn't use 
it. But there are other library functions that would make your code 
more concise, more readable, and maybe faster.


Starting with shuffle() (which I'd call ripple())

Because Python makes it easy to swap two variables in-place, it's common 
to swap arguments directly, rather than copy them to local attributes. 
So I'd replace the first 4 lines with:
if self.rgen.randint(0,1): #randomly decide which pile is shuffled 
down first

inpile2, inpile1 = inpile1, inpile2

len() is very fast, so there's no need for a separate variable to keep 
track of the lengths of inpile1 and inpile2. So eliminate all refs to 
pile1c and pile2. In the while, just use

while len(inpile1) and len(inpile2):

Lists have no type associated with them. Each object in a list has its 
own type. So there's no meaning to constructing an empty list out of 
another one.

rpile = []

pop(0) is slow, compared with pop(-1). If you used the latter, you 
would have to do a reverse on the list when you were done to keep the 
realism. And that would make the code less readable. So I think this 
is an unnecessary optimization. But keep it in mind if you're ever 
dealing with thousands of items in a list. Peeling them off from the 
front one at a time will be slow.


The logic of popping a random number of cards from one list, and 
appending them to the result could be done the same way you do the 
cut(), using slices. I think it would be worth it if you made a 
separate function out of it, to call from whichever deck was being 
operated on.


Where you do the if i < pile1c you could instead use the min() 
function.

i = min(len(inpile1), self.rgen.randint(1,4))

At the end of the function, the if pile1c: elif ... logic could be 
replaced by

rpile.extend(inpile1).extend(inpile2)

as there's no harm in extending with an empty list.

HTH, DaveA





Dave and Alan,

 


Thank you for the advice and showing me some of the small nuances I haven't 
quite figured out yet. I used both of your suggestions to change the class the 
updated code is attached if you'd like to see.

 

I tried putting the two extends in the same line and that didn't work as extend doesn't return anything so ended up putting them on consecutive lines without the if statement. 

 

Instead of doing the pop method I took your advice and tried it with slices instead along with extends. Shortened the code a bit. One note on pop method is pop() and pop(-1) the same thing? Looks like it based on what I've read but not 100% confident in that answer. 

 


On the class versus module I wasn't sure where I'd end up taking this idea so 
went ahead and coded it as a class. If I actually do much more with this, other 
then just as a coding exercise to help learn Python, I might be adding things 
to this or using it as a superclass. Examples of expansion ability to queue up 
decks, have multiple shufflers going at the same time in a program etc... So 
without knowing all the options in Python figured the class gave me the 
greatest flexibility. Yeah otherwise I'd have just made a module and still 
might switch it if I expand on this depending on what the needs turn out to be.

 


Again thanks to everyone for looking at my code and the quick and helpful 
feedback. Hoping to do start coding a larger project soon so you'll probably 
get some questions from me.

 


Thanks,

Brian

  
You're certainly welcome.  Sorry I blew it on extend().  I should have 
known better; not just remembered.  Python is pretty consistent - when a 
method modifies its self-data, it generally doesn't return it as well.  
For example sort() returns None, while sorted() returns the new list.


As for pop(-1):  it'll always take from the end of the list, rather than 
the beginning for pop(0).  That's faster, but the result ends up 
backwards.  So you call reverse() on the result to get it back to where 
you began.  I hope I pointed out that it's a minor optimization for 
small lists, and that it might

Re: [Tutor] renaming files within a directory

2009-07-27 Thread Kent Johnson
On Mon, Jul 27, 2009 at 5:10 AM,  wrote:

> files = set([file for file in os.listdir(os.getcwd()) if 
> file.endswith('svg')])
> print len(files)
>
> for file in files:
>    file = file.strip('.svg')
>    print file
> #    if countries.has_key(file):
> #       print file
>
> When I run this I get:
>
> Flag_of_Uganda
> ...
>
> The problem is that for example the file Flag_of_the_United_States.svg when I 
> use the strip('.svg') it is returned as Flag_of_the_United_State
>
> Also, How do I remove 'Flag_of', 'Flag_of_the_'

I suggest you use glob.glob() instead of os.listdir():

files = glob.glob('Flag_of_*.svg)

Then you know that each file name starts with Flag_of_ and ends with
.svg. To remove them, since they are fixed strings you can just use
slicing;
file = file[8:-4]
if file.startswith('the_'):
  file = file[4:]

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Gregor Lingl

Dick Moores schrieb:

I've taken a long break from Python, and now I want to try scripting
with 2.62. I downloaded and installed 2.62, changed Win XP
environmental variables to use Python26. Entering python at the
command line shows I'm using 2.62:

C:\Documents and Settings\Riley>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
  


So I'm able to try out the new features of 2.6 (I had been using
2.51), but I can't get IDLE to use 2.6. When I click on
E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

And of course, the new 2.6 features don't work.

Advice, please.
  

I suggest you have to change the association of *.pyw files to the
program, which is used to 'open' it.

In Windows explorer choose menu extras/directory options,
then choose tab file types and select PYW type
then press button 'advacned...' or somethng like this at the bottom
of the tab, chose 'open' and the button to change this.

If you see the entry

"C:\Python25\pythonw.exe" "%1" %*

change this to Python26

My translations from the German button captions to
English might not be correct. Hope this helps anyway.

Regards,
Gregor



Thanks,

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


  


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread davidwilson
Here is the updated viersion:

---

import glob
import csv
from os import rename


countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in glob.glob('Flag_of_*.svg')])

for file in files:
file = file[8:-4]
if file.startswith('the_'):
file = file[4:]
if countries.has_key(file):
b = 'flag-'+ countries[file] + '.svg'
print b
rename(file, b)

But I cannot get the rename to take effect and I get an error:

$ python rename_svg.py 
Uganda flag-ug.svg
Traceback (most recent call last):
  File "rename_svg.py", line 21, in 
rename(file, b)
OSError: [Errno 2] No such file or directory

What am I missing?

 Original Message 
From: Kent Johnson 
Apparently from: kent3...@gmail.com
To: davidwil...@safe-mail.net
Cc: m...@timgolden.me.uk, tutor@python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Mon, 27 Jul 2009 07:01:32 -0400

> On Mon, Jul 27, 2009 at 5:10 AM,  wrote:
> 
> > files = set([file for file in os.listdir(os.getcwd()) if 
> > file.endswith('svg')])
> > print len(files)
> >
> > for file in files:
> >    file = file.strip('.svg')
> >    print file
> > #    if countries.has_key(file):
> > #       print file
> >
> > When I run this I get:
> >
> > Flag_of_Uganda
> > ...
> >
> > The problem is that for example the file Flag_of_the_United_States.svg when 
> > I use the strip('.svg') it is returned as Flag_of_the_United_State
> >
> > Also, How do I remove 'Flag_of', 'Flag_of_the_'
> 
> I suggest you use glob.glob() instead of os.listdir():
> 
> files = glob.glob('Flag_of_*.svg)
> 
> Then you know that each file name starts with Flag_of_ and ends with
> .svg. To remove them, since they are fixed strings you can just use
> slicing;
> file = file[8:-4]
> if file.startswith('the_'):
>   file = file[4:]
> 
> Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Christian Witts

davidwil...@safe-mail.net wrote:

Here is the updated viersion:

---

import glob
import csv
from os import rename


countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in glob.glob('Flag_of_*.svg')])

for file in files:
file = file[8:-4]
if file.startswith('the_'):
file = file[4:]
if countries.has_key(file):
b = 'flag-'+ countries[file] + '.svg'
print b
rename(file, b)

But I cannot get the rename to take effect and I get an error:

$ python rename_svg.py 
Uganda flag-ug.svg

Traceback (most recent call last):
  File "rename_svg.py", line 21, in 
rename(file, b)
OSError: [Errno 2] No such file or directory

What am I missing?

 Original Message 
From: Kent Johnson 
Apparently from: kent3...@gmail.com
To: davidwil...@safe-mail.net
Cc: m...@timgolden.me.uk, tutor@python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Mon, 27 Jul 2009 07:01:32 -0400

  

On Mon, Jul 27, 2009 at 5:10 AM,  wrote:



files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])
print len(files)

for file in files:
   file = file.strip('.svg')
   print file
#if countries.has_key(file):
#   print file

When I run this I get:

Flag_of_Uganda
...

The problem is that for example the file Flag_of_the_United_States.svg when I 
use the strip('.svg') it is returned as Flag_of_the_United_State

Also, How do I remove 'Flag_of', 'Flag_of_the_'
  

I suggest you use glob.glob() instead of os.listdir():

files = glob.glob('Flag_of_*.svg)

Then you know that each file name starts with Flag_of_ and ends with
.svg. To remove them, since they are fixed strings you can just use
slicing;
file = file[8:-4]
if file.startswith('the_'):
  file = file[4:]

Kent


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  
You changed the name contained in file from the original so it now 
cannot find what you are referring to.  Try not to shadow built-in names 
like file by the way, it can cause unintended side-effects.


Make changes to this effect:

for filename in files:
   fn = filename[8:-4]
   if fn.startswith('the_'):
   fn = fn[4:]
   if fn in countries:   # Dictionaries can be accessed this way and it 
looks cleaner.
   new_filename = 'flag-%s.svg' % countries[fn]  # String 
formatting is neater and faster than concatenation

   rename(filename, new_filename)

--
Kind Regards,
Christian Witts


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Dave Angel

davidwil...@safe-mail.net wrote:

Here is the updated viersion:

---

import glob
import csv
from os import rename


countries =}
reader =sv.reader(open("countries.csv"))
for row in reader:
code, name =ow
countries[name] =ode

files =et([file for file in glob.glob('Flag_of_*.svg')])

for file in files:
file =ile[8:-4]
if file.startswith('the_'):
file =ile[4:]
if countries.has_key(file):
b =flag-'+ countries[file] + '.svg'
print b
rename(file, b)

But I cannot get the rename to take effect and I get an error:

$ python rename_svg.py 
Uganda flag-ug.svg

Traceback (most recent call last):
  File "rename_svg.py", line 21, in 
rename(file, b)
OSError: [Errno 2] No such file or directory

What am I missing?

 Original Message 
From: Kent Johnson 
Apparently from: kent3...@gmail.com
To: davidwil...@safe-mail.net
Cc: m...@timgolden.me.uk, tutor@python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Mon, 27 Jul 2009 07:01:32 -0400

  

On Mon, Jul 27, 2009 at 5:10 AM,  wrote:



files =et([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])
print len(files)

for file in files:
   file =ile.strip('.svg')
   print file
#if countries.has_key(file):
#   print file

When I run this I get:

Flag_of_Uganda
...

The problem is that for example the file Flag_of_the_United_States.svg when I 
use the strip('.svg') it is returned as Flag_of_the_United_State

Also, How do I remove 'Flag_of', 'Flag_of_the_'
  

I suggest you use glob.glob() instead of os.listdir():

files =lob.glob('Flag_of_*.svg)

Then you know that each file name starts with Flag_of_ and ends with
.svg. To remove them, since they are fixed strings you can just use
slicing;
file =ile[8:-4]
if file.startswith('the_'):
  file =ile[4:]

Kent



(Please don't top-post on this mailing list.  It hopelessly confuses which 
order the quoted messages come.)
  


One reason the rename() will fail is that you're changing file between 
the for loop and the rename.  Incidentally, file is a lousy name to use, 
since it already has a meaning in the std lib.  It's the type of the 
object you get from open(), or from glob.glog().



I didn't check the rest, but for this change, you'd get:

for infile in files:
   country = infile[8:-4]
   if country.startswith('the_'):
country = country[4:]
   if countries.has_key(file):
b = 'flag-'+ countries[country] + '.svg'
print b
rename(file, b)


BTW, several other characters were dropped in your email.  Did you 
retype the code (bad), or use cut/paste?


DaveA

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dave Angel

Gregor Lingl wrote:
Dick 
Moores schrieb:

I've taken a long break from Python, and now I want to try scripting
with 2.62. I downloaded and installed 2.62, changed Win XP
environmental variables to use Python26. Entering python at the
command line shows I'm using 2.62:

C:\Documents and Settings\Riley>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 
So I'm able to try out the new features of 2.6 (I had been using

2.51), but I can't get IDLE to use 2.6. When I click on
E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

And of course, the new 2.6 features don't work.

Advice, please.
  

I suggest you have to change the association of *.pyw files to the
program, which is used to 'open' it.

In Windows explorer choose menu extras/directory options,
then choose tab file types and select PYW type
then press button 'advacned...' or somethng like this at the bottom
of the tab, chose 'open' and the button to change this.

If you see the entry

"C:\Python25\pythonw.exe" "%1" %*

change this to Python26

My translations from the German button captions to
English might not be correct. Hope this helps anyway.

Regards,
Gregor



Thanks,

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


  


For future reference, assoc and ftype are commandline tools that let you 
examine and modify those file associations.  Very useful if you have to 
go back and forth between two versions.


DaveA

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dick Moores
On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote:
> Dick Moores schrieb:
>>
>> I've taken a long break from Python, and now I want to try scripting
>> with 2.62. I downloaded and installed 2.62, changed Win XP
>> environmental variables to use Python26. Entering python at the
>> command line shows I'm using 2.62:
>>
>> C:\Documents and Settings\Riley>python
>> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
>> (Intel)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>>
>> So I'm able to try out the new features of 2.6 (I had been using
>> 2.51), but I can't get IDLE to use 2.6. When I click on
>> E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
>> (Intel)] on win32
>> Type "copyright", "credits" or "license()" for more information.
>>
>> And of course, the new 2.6 features don't work.
>>
>> Advice, please.
>>
>
> I suggest you have to change the association of *.pyw files to the
> program, which is used to 'open' it.
>
> In Windows explorer choose menu extras/directory options,
> then choose tab file types and select PYW type
> then press button 'advacned...' or somethng like this at the bottom
> of the tab, chose 'open' and the button to change this.
>
> If you see the entry
>
> "C:\Python25\pythonw.exe" "%1" %*
>
> change this to Python26

Yes! After I did that, now when I call
E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.

But I also want to use Ulipad, actually my main Python editor. When I
call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
Ulipad no longer opens. Before I made the change you suggested, at
least Ulipad would open using 2.51. What can I do to use both IDLE and
Ulipad with 2.62?

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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread davidwilson
Thank you all for your help.

 Original Message 
From: Dave Angel 
Apparently from: srs0=pajg=du=ieee.org=da...@srs.perfora.net
To: davidwil...@safe-mail.net
Cc: ken...@tds.net, tutor@python.org
Subject: Re: Re: [Tutor] renaming files within a directory
Date: Mon, 27 Jul 2009 09:01:58 -0400

> davidwil...@safe-mail.net wrote:
> > Here is the updated viersion:
> >
> > ---
> >
> > import glob
> > import csv
> > from os import rename
> >
> >
> > countries =}
> > reader =sv.reader(open("countries.csv"))
> > for row in reader:
> > code, name =ow
> > countries[name] =ode
> >
> > files =et([file for file in glob.glob('Flag_of_*.svg')])
> >
> > for file in files:
> > file =ile[8:-4]
> > if file.startswith('the_'):
> > file =ile[4:]
> > if countries.has_key(file):
> > b =flag-'+ countries[file] + '.svg'
> > print b
> > rename(file, b)
> >
> > But I cannot get the rename to take effect and I get an error:
> >
> > $ python rename_svg.py 
> > Uganda flag-ug.svg
> > Traceback (most recent call last):
> >   File "rename_svg.py", line 21, in 
> > rename(file, b)
> > OSError: [Errno 2] No such file or directory
> >
> > What am I missing?
> >
> >  Original Message 
> > From: Kent Johnson 
> > Apparently from: kent3...@gmail.com
> > To: davidwil...@safe-mail.net
> > Cc: m...@timgolden.me.uk, tutor@python.org
> > Subject: Re: [Tutor] renaming files within a directory
> > Date: Mon, 27 Jul 2009 07:01:32 -0400
> >
> >   
> >> On Mon, Jul 27, 2009 at 5:10 AM,  wrote:
> >>
> >> 
> >>> files =et([file for file in os.listdir(os.getcwd()) if 
> >>> file.endswith('svg')])
> >>> print len(files)
> >>>
> >>> for file in files:
> >>>file =ile.strip('.svg')
> >>>print file
> >>> #if countries.has_key(file):
> >>> #   print file
> >>>
> >>> When I run this I get:
> >>>
> >>> Flag_of_Uganda
> >>> ...
> >>>
> >>> The problem is that for example the file Flag_of_the_United_States.svg 
> >>> when I use the strip('.svg') it is returned as Flag_of_the_United_State
> >>>
> >>> Also, How do I remove 'Flag_of', 'Flag_of_the_'
> >>>   
> >> I suggest you use glob.glob() instead of os.listdir():
> >>
> >> files =lob.glob('Flag_of_*.svg)
> >>
> >> Then you know that each file name starts with Flag_of_ and ends with
> >> .svg. To remove them, since they are fixed strings you can just use
> >> slicing;
> >> file =ile[8:-4]
> >> if file.startswith('the_'):
> >>   file =ile[4:]
> >>
> >> Kent
> >> 
> >
> > (Please don't top-post on this mailing list.  It hopelessly confuses which 
> > order the quoted messages come.)
> >   
> 
> One reason the rename() will fail is that you're changing file between 
> the for loop and the rename.  Incidentally, file is a lousy name to use, 
> since it already has a meaning in the std lib.  It's the type of the 
> object you get from open(), or from glob.glog().
> 
> 
> I didn't check the rest, but for this change, you'd get:
> 
> for infile in files:
> country = infile[8:-4]
> if country.startswith('the_'):
>   country = country[4:]
> if countries.has_key(file):
>   b = 'flag-'+ countries[country] + '.svg'
>   print b
>   rename(file, b)
> 
> 
> BTW, several other characters were dropped in your email.  Did you 
> retype the code (bad), or use cut/paste?

I just cut and paste from vim.

Here is the final code:

import glob
import csv
from os import rename


countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in glob.glob('Flag_of_*.svg')])

for filename in files:
fn = filename[8:-4]
if fn.startswith('the_'):
fn = fn[4:]
if fn in countries:
new_filename = 'flag-%s.svg' % countries[fn]
rename(filename, new_filename)


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


Re: [Tutor] renaming files within a directory

2009-07-27 Thread Alan Gauld


 wrote 




files = set([file for file in glob.glob('Flag_of_*.svg')])

for file in files:
   file = file[8:-4]


Yu probably want to keep the filename unouched and 
use a variable like country here.



   if file.startswith('the_'):
file = file[4:]
   if countries.has_key(file):
b = 'flag-'+ countries[file] + '.svg'
print b
rename(file, b)


You are trying to use file in the rename but you have 
modified the filename so it is no longer valid. I'd use 
filename as the variable in the for loop and country 
for the modified version used to access the dictionary.


$ python rename_svg.py 
Uganda flag-ug.svg


Where does the Uganda come from? Loooks like the 
real code has an extra print statement somewhere?



HTH,


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

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Alan Gauld


"Dick Moores"  wrote


I suggest you have to change the association of *.pyw files to the
program, which is used to 'open' it.


Yes! After I did that, now when I call
E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.

But I also want to use Ulipad, actually my main Python editor. When I
call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
Ulipad no longer opens. Before I made the change you suggested, at
least Ulipad would open using 2.51. What can I do to use both IDLE and
Ulipad with 2.62?


What I do for these things is create a shortcut which specifies 
the full path to the interpreter and to the pyw file. I also set the 
working foldeer to wherever is most appropriate - usually my 
project folder. That's fairly bulletproof in my experience!


HTH,


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

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


[Tutor] problem with csv dictreader

2009-07-27 Thread Eduardo Vieira
Hello, I'm enjoying learning python but then I come across some basic
things that makes me stumped... I have 2 csv files and I want to see
which ones are duplicates based on two criteria email, or telephone.
The order of fields in both csv files are different. Here are a sample
bogus data:

import csv

bv = """NAME,BVADDRTELNO1,BVADDREMAIL
Company1, 1234567788, t...@that.com
CompanyA, 1231234455, t...@this.com
CompanyC, 101101, n...@this.com
CompanyD, 22, o...@olde.com

"""
site = """Company,Email,Phone
"Company3","noth...@nada.com","123456"
"CompanyD","o...@olde.com","22"
"Company1","t...@that.com","1234567788"
"""

bv = bv.upper() # This is just to make the data more homogeneous and
detect duplicates more easily

site = site.upper()


bvreader = csv.DictReader(bv.splitlines(True))

sitelist = csv.DictReader(site.splitlines(True))


for row in sitelist:
for line in bvreader:
if row['EMAIL'] == line['BVADDREMAIL']:
print line['NAME'], row['COMPANY']

#=
My questions are:
Why nothing is being printed? Two rows should be printed right?
What would be better for the outer loop, the bigger list or the small
list? The biglist (bvreader) is under 2100 lines (244Kb) and the
smaller list (sitelist) can be 20 lines or less.

Thanks.

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


[Tutor] subprocess.call

2009-07-27 Thread davidwilson
Hello again,
>From my previous post I would now like to transform the SVG images using the 
>svg2png library, but am having difficulties in making it work. Here is the 
>code:

import glob
import csv
from os import rename
import subprocess

countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
code, name = row
countries[name] = code

files = set([file for file in glob.glob('Flag_of_*.svg')])

for filename in files:
fn = filename[8:-4]
if fn.startswith('the_'):
fn = fn[4:]
if fn in countries:
new_filename = 'flag-%s' % countries[fn]

subprocess.call(['svg2png --width=17 --height=12 %s %s' \
% (filename, new_filename  + '.png')])

$ python rename_svg.py 
Traceback (most recent call last):
  File "rename_svg.py", line 22, in 
% (filename, new_filename  + '.png')])
  File "/home/dwilson/usr/local/python2.6/lib/python2.6/subprocess.py", line 
444, in call
return Popen(*popenargs, **kwargs).wait()
  File "/home/dwilson/usr/local/python2.6/lib/python2.6/subprocess.py", line 
595, in __init__
errread, errwrite)
  File "/home/dwilson/usr/local/python2.6/lib/python2.6/subprocess.py", line 
1092, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

Where am I doing this wrong?

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


[Tutor] Eng to Leet Speek

2009-07-27 Thread Chris Castillo
so I have a string:

1 4|-| 50 |_33+.  I love [#ick3n 4nd ch3353.  Don't you love +|_|2|\e7
\/\/1+# the |#a|-|i|_7?


and I am trying to turn it into english with the following code:

fileIn = open("encrypted.txt", "r").read()

def eng2leet(astring):
astring = astring.replace("4","a")
astring = astring.replace("8","b")
astring = astring.replace("[","c")
astring = astring.replace("|)","d")
astring = astring.replace("3","e")
astring = astring.replace("|#","f")
astring = astring.replace("6","g")
astring = astring.replace("#","h")
astring = astring.replace("1","i")
astring = astring.replace("]","j")
astring = astring.replace("|\\","k")
astring = astring.replace("|_","l")
astring = astring.replace("|-|","m")
astring = astring.replace("|\\","n")
astring = astring.replace("0","o")
astring = astring.replace("|*","p")
astring = astring.replace("0\\","q")
astring = astring.replace("2","r")
astring = astring.replace("5","s")
astring = astring.replace("+","t")
astring = astring.replace("|_|","u")
astring = astring.replace("\/","v")
astring = astring.replace("\/\/","w")
astring = astring.replace("><","x")
astring = astring.replace("7","y")
astring = astring.replace("7_","z")
return astring

print eng2leet(fileIn)

Only problem is that when it needs to translate a U or a W it prints an L or
2 V's. Need some help please. Thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dave Angel

Dick Moores wrote:

On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote:
  

Dick Moores schrieb:


I've taken a long break from Python, and now I want to try scripting
with 2.62. I downloaded and installed 2.62, changed Win XP
environmental variables to use Python26. Entering python at the
command line shows I'm using 2.62:

C:\Documents and Settings\Riley>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

So I'm able to try out the new features of 2.6 (I had been using
2.51), but I can't get IDLE to use 2.6. When I click on
E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

And of course, the new 2.6 features don't work.

Advice, please.

  

I suggest you have to change the association of *.pyw files to the
program, which is used to 'open' it.

In Windows explorer choose menu extras/directory options,
then choose tab file types and select PYW type
then press button 'advacned...' or somethng like this at the bottom
of the tab, chose 'open' and the button to change this.

If you see the entry

"C:\Python25\pythonw.exe" "%1" %*

change this to Python26



Yes! After I did that, now when I call
E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.

But I also want to use Ulipad, actually my main Python editor. When I
call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
Ulipad no longer opens. Before I made the change you suggested, at
least Ulipad would open using 2.51. What can I do to use both IDLE and
Ulipad with 2.62?

Dick

  


I don't know IDLE, so I don't really know how it decides which Python to 
use.  In this thread Gregor suggested fixing the file association, which 
is certainly reasonable.  And I suggested what to me is an easier way to 
fix associations.  But there may be another way that I just don't know 
about, such as some environment variable.  You could send email to 
idle-...@python.org.   One other thought:  Idle.bat is located in the 
install directory of python.  So perhaps it locates the python that it's 
running with.  Could you try running it more explicitly?  Make your own 
bat file that instead of

   start idle.pyw %1 %2 %3 %4 %5 %6 %7 %8 %9
looks like
   e:
   cd \Python26\Lib\idlelib\
   ..\..\pythonw.exe idle.pyw %*


I do know that when you double-click on a xxx.pyw file in Explorer, it 
will use the association to decide which program, and there's only one 
program you can have there.  My preference is to have it execute the 
program, not start IDLE, a text editor, or any IDE.   You may feel 
differently, but if you agree with me, then you might want to add 
UliPad.exe in the context menu of explorer.  If you do that 
successfully, then when you right-click on a .pyw file, one of your 
choices will be "Run Ulipad."


The following is pretty-much pasted from some notes I took quite a while 
ago, and may not be quite right.  So if you're not pretty familiar with 
the registry, you probably shouldn't experiment just based on this.


>>>In the Windows registry, add a new key under 
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell

>>>Make its default value the item text you want in the context menu.
>>>Add a new key under it, "command", and make its default value the 
command line you want to execute. Will look like this:

>>>"complete path to ulipad.exe"  %1 %*
>>>See http://msdn.microsoft.com/en-us/library/dd807139(VS.85).aspx for 
more details


In addition to adding it to right-click menu, you could also add it to 
the "open-with" list, or to "Send-To" list.  I don't have any cookbook 
for any of these, but I've done each at one time or another.


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


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread J Sisson
You need a deterministic algorithm for conversion.  It's impossible (without
analyzing the context of the word) to translate "|_|#" (it's either "lf" or
"uh", but which?).




On Mon, Jul 27, 2009 at 1:13 PM, Chris Castillo  wrote:

> so I have a string:
>
> 1 4|-| 50 |_33+.  I love [#ick3n 4nd ch3353.  Don't you love +|_|2|\e7
> \/\/1+# the |#a|-|i|_7?
>
>
> and I am trying to turn it into english with the following code:
>
> fileIn = open("encrypted.txt", "r").read()
>
> def eng2leet(astring):
> astring = astring.replace("4","a")
> astring = astring.replace("8","b")
> astring = astring.replace("[","c")
> astring = astring.replace("|)","d")
> astring = astring.replace("3","e")
> astring = astring.replace("|#","f")
> astring = astring.replace("6","g")
> astring = astring.replace("#","h")
> astring = astring.replace("1","i")
> astring = astring.replace("]","j")
> astring = astring.replace("|\\","k")
> astring = astring.replace("|_","l")
> astring = astring.replace("|-|","m")
> astring = astring.replace("|\\","n")
> astring = astring.replace("0","o")
> astring = astring.replace("|*","p")
> astring = astring.replace("0\\","q")
> astring = astring.replace("2","r")
> astring = astring.replace("5","s")
> astring = astring.replace("+","t")
> astring = astring.replace("|_|","u")
> astring = astring.replace("\/","v")
> astring = astring.replace("\/\/","w")
> astring = astring.replace("><","x")
> astring = astring.replace("7","y")
> astring = astring.replace("7_","z")
> return astring
>
> print eng2leet(fileIn)
>
> Only problem is that when it needs to translate a U or a W it prints an L
> or 2 V's. Need some help please. Thanks
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Computers are like air conditioners...
They quit working when you open Windows.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess.call

2009-07-27 Thread davidwilson
OK I think I found my error, here is what I did:

flags = set([file for file in glob.glob('flag-*.svg')])

def call(cmd):
subprocess.call([cmd], shell=True)

for flag in flags:
name = flag[:-4]
out = name+'.png'
call('svg2png --width=17 --height=12 %s %s' \
   % (flag, out))

Is this better?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dave Angel

Dick Moores wrote:

On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote:
  

Dick Moores schrieb:


I've taken a long break from Python, and now I want to try scripting
with 2.62. I downloaded and installed 2.62, changed Win XP
environmental variables to use Python26. Entering python at the
command line shows I'm using 2.62:

C:\Documents and Settings\Riley>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

So I'm able to try out the new features of 2.6 (I had been using
2.51), but I can't get IDLE to use 2.6. When I click on
E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

And of course, the new 2.6 features don't work.

Advice, please.

  

I suggest you have to change the association of *.pyw files to the
program, which is used to 'open' it.

In Windows explorer choose menu extras/directory options,
then choose tab file types and select PYW type
then press button 'advacned...' or somethng like this at the bottom
of the tab, chose 'open' and the button to change this.

If you see the entry

"C:\Python25\pythonw.exe" "%1" %*

change this to Python26



Yes! After I did that, now when I call
E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.

But I also want to use Ulipad, actually my main Python editor. When I
call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
Ulipad no longer opens. Before I made the change you suggested, at
least Ulipad would open using 2.51. What can I do to use both IDLE and
Ulipad with 2.62?

Dick

  


I don't know IDLE, so I don't really know how it decides which Python to 
use.  In this thread Gregor suggested fixing the file association, which 
is certainly reasonable.  And I suggested what to me is an easier way to 
fix associations.  But there may be another way that I just don't know 
about, such as some environment variable.  You could send email to 
idle-...@python.org.   One other thought:  Idle.bat is located in the 
install directory of python.  So perhaps it locates the python that it's 
running with.  Could you try running it more explicitly?  Make your own 
bat file that instead of

   start idle.pyw %1 %2 %3 %4 %5 %6 %7 %8 %9
looks like
   e:
   cd \Python26\Lib\idlelib\
   ..\..\pythonw.exe idle.pyw %*


I do know that when you double-click on a xxx.pyw file in Explorer, it 
will use the association to decide which program, and there's only one 
program you can have there.  My preference is to have it execute the 
program, not start IDLE, a text editor, or any IDE.   You may feel 
differently, but if you agree with me, then you might want to add 
UliPad.exe in the context menu of explorer.  If you do that 
successfully, then when you right-click on a .pyw file, one of your 
choices will be "Run Ulipad."


The following is pretty-much pasted from some notes I took quite a while 
ago, and may not be quite right.  So if you're not pretty familiar with 
the registry, you probably shouldn't experiment just based on this.


>>>In the Windows registry, add a new key under 
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell

>>>Make its default value the item text you want in the context menu.
>>>Add a new key under it, "command", and make its default value the 
command line you want to execute. Will look like this:

>>>"complete path to ulipad.exe"  %1 %*
>>>See http://msdn.microsoft.com/en-us/library/dd807139(VS.85).aspx for 
more details


In addition to adding it to right-click menu, you could also add it to 
the "open-with" list, or to "Send-To" list.  I don't have any cookbook 
for any of these, but I've done each at one time or another.


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


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread Chris Castillo
On Mon, Jul 27, 2009 at 1:38 PM, J Sisson  wrote:

> You need a deterministic algorithm for conversion.  It's impossible
> (without analyzing the context of the word) to translate "|_|#" (it's either
> "lf" or "uh", but which?).
>
>
>
>
> On Mon, Jul 27, 2009 at 1:13 PM, Chris Castillo  wrote:
>
>> so I have a string:
>>
>> 1 4|-| 50 |_33+.  I love [#ick3n 4nd ch3353.  Don't you love +|_|2|\e7
>> \/\/1+# the |#a|-|i|_7?
>>
>>
>> and I am trying to turn it into english with the following code:
>>
>> fileIn = open("encrypted.txt", "r").read()
>>
>> def eng2leet(astring):
>> astring = astring.replace("4","a")
>> astring = astring.replace("8","b")
>> astring = astring.replace("[","c")
>> astring = astring.replace("|)","d")
>> astring = astring.replace("3","e")
>> astring = astring.replace("|#","f")
>> astring = astring.replace("6","g")
>> astring = astring.replace("#","h")
>> astring = astring.replace("1","i")
>> astring = astring.replace("]","j")
>> astring = astring.replace("|\\","k")
>> astring = astring.replace("|_","l")
>> astring = astring.replace("|-|","m")
>> astring = astring.replace("|\\","n")
>> astring = astring.replace("0","o")
>> astring = astring.replace("|*","p")
>> astring = astring.replace("0\\","q")
>> astring = astring.replace("2","r")
>> astring = astring.replace("5","s")
>> astring = astring.replace("+","t")
>> astring = astring.replace("|_|","u")
>> astring = astring.replace("\/","v")
>> astring = astring.replace("\/\/","w")
>> astring = astring.replace("><","x")
>> astring = astring.replace("7","y")
>> astring = astring.replace("7_","z")
>> return astring
>>
>> print eng2leet(fileIn)
>>
>> Only problem is that when it needs to translate a U or a W it prints an L
>> or 2 V's. Need some help please. Thanks
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
> --
> Computers are like air conditioners...
> They quit working when you open Windows.



so is their some other way to go about this?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread Dave Angel

Chris Castillo wrote:

so I have a string:

1 4|-| 50 |_33+.  I love [#ick3n 4nd ch3353.  Don't you love +|_|2|\e7
\/\/1+# the |#a|-|i|_7?


and I am trying to turn it into english with the following code:

fileIn = open("encrypted.txt", "r").read()

def eng2leet(astring):
astring = astring.replace("4","a")
astring = astring.replace("8","b")
astring = astring.replace("[","c")
astring = astring.replace("|)","d")
astring = astring.replace("3","e")
astring = astring.replace("|#","f")
astring = astring.replace("6","g")
astring = astring.replace("#","h")
astring = astring.replace("1","i")
astring = astring.replace("]","j")
astring = astring.replace("|\\","k")
astring = astring.replace("|_","l")
astring = astring.replace("|-|","m")
astring = astring.replace("|\\","n")
astring = astring.replace("0","o")
astring = astring.replace("|*","p")
astring = astring.replace("0\\","q")
astring = astring.replace("2","r")
astring = astring.replace("5","s")
astring = astring.replace("+","t")
astring = astring.replace("|_|","u")
astring = astring.replace("\/","v")
astring = astring.replace("\/\/","w")
astring = astring.replace("><","x")
astring = astring.replace("7","y")
astring = astring.replace("7_","z")
return astring

print eng2leet(fileIn)

Only problem is that when it needs to translate a U or a W it prints an L or
2 V's. Need some help please. Thanks

  
Your problem is in the order of substitution.  If you put the "v" test 
*after* the "w" test, you'll avoid one of your problems.  And put the 
"l" test after the "u" test.   And you didn't mention it, but "z" should 
come before "y".  This is because some of your strings are substrings of 
others.  A more general rule might be to put all the four-character 
substitutions first, then do all the three-character ones, then two, 
then one.  That's not guaranteed to work, but by inspection I think it will.


Another problem that could have hit you is that "\" is an escape 
character in strings.  So you're taking advantage of the fact that \/ 
(for example) doesn't happen to be a valid escape sequence.  The usual 
workaround is to use raw strings.   For another example, look at the 
string for "n".  Did you want two backslashes?  You'll only get one as 
it sits.


Did you mean for "k" and "n" to be the same?

DaveA

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dick Moores
On Mon, Jul 27, 2009 at 09:32, Alan Gauld wrote:
>
> "Dick Moores"  wrote
>
>>> I suggest you have to change the association of *.pyw files to the
>>> program, which is used to 'open' it.
>>>
>> Yes! After I did that, now when I call
>> E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.
>>
>> But I also want to use Ulipad, actually my main Python editor. When I
>> call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
>> Ulipad no longer opens. Before I made the change you suggested, at
>> least Ulipad would open using 2.51. What can I do to use both IDLE and
>> Ulipad with 2.62?
>
> What I do for these things is create a shortcut which specifies the full
> path to the interpreter and to the pyw file. I also set the working foldeer
> to wherever is most appropriate - usually my project folder. That's fairly
> bulletproof in my experience!

Alan, here's what have now to call Ulipad: the shortcut shown at
. It opens Ulipad, but
a Ulipad that uses 2.51, not 2.62 in its shell, but does use 2.62 to
run scripts (Ulipad asked me which interpreter I wanted to use for
that). So it seems I've almost got Ulipad where I want it. Perhaps the
developer can help me get its shell to use 2.62 as well.

I made a shortcut for IDLE that opens an IDLE that uses
2.62 (it's image is at ).

Thanks,

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


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread Chris Castillo
On Mon, Jul 27, 2009 at 2:08 PM, Dave Angel  wrote:

> Chris Castillo wrote:
>
>> so I have a string:
>>
>> 1 4|-| 50 |_33+.  I love [#ick3n 4nd ch3353.  Don't you love +|_|2|\e7
>> \/\/1+# the |#a|-|i|_7?
>>
>>
>> and I am trying to turn it into english with the following code:
>>
>> fileIn = open("encrypted.txt", "r").read()
>>
>> def eng2leet(astring):
>>astring = astring.replace("4","a")
>>astring = astring.replace("8","b")
>>astring = astring.replace("[","c")
>>astring = astring.replace("|)","d")
>>astring = astring.replace("3","e")
>>astring = astring.replace("|#","f")
>>astring = astring.replace("6","g")
>>astring = astring.replace("#","h")
>>astring = astring.replace("1","i")
>>astring = astring.replace("]","j")
>>astring = astring.replace("|\\","k")
>>astring = astring.replace("|_","l")
>>astring = astring.replace("|-|","m")
>>astring = astring.replace("|\\","n")
>>astring = astring.replace("0","o")
>>astring = astring.replace("|*","p")
>>astring = astring.replace("0\\","q")
>>astring = astring.replace("2","r")
>>astring = astring.replace("5","s")
>>astring = astring.replace("+","t")
>>astring = astring.replace("|_|","u")
>>astring = astring.replace("\/","v")
>>astring = astring.replace("\/\/","w")
>>astring = astring.replace("><","x")
>>astring = astring.replace("7","y")
>>astring = astring.replace("7_","z")
>>return astring
>>
>> print eng2leet(fileIn)
>>
>> Only problem is that when it needs to translate a U or a W it prints an L
>> or
>> 2 V's. Need some help please. Thanks
>>
>>
>>
> Your problem is in the order of substitution.  If you put the "v" test
> *after* the "w" test, you'll avoid one of your problems.  And put the "l"
> test after the "u" test.   And you didn't mention it, but "z" should come
> before "y".  This is because some of your strings are substrings of others.
>  A more general rule might be to put all the four-character substitutions
> first, then do all the three-character ones, then two, then one.  That's not
> guaranteed to work, but by inspection I think it will.
>
> Another problem that could have hit you is that "\" is an escape character
> in strings.  So you're taking advantage of the fact that \/ (for example)
> doesn't happen to be a valid escape sequence.  The usual workaround is to
> use raw strings.   For another example, look at the string for "n".  Did you
> want two backslashes?  You'll only get one as it sits.
>
> Did you mean for "k" and "n" to be the same?
>
> DaveA
>
> Yes that solved it and caught all exceptions (after changing the typo I had
for the n) I really did not think about changing the order like that. I feel
stupid for not thinking of that. Thank you for your insight.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess.call

2009-07-27 Thread Sander Sweers
On Mon, 2009-07-27 at 14:40 -0400, davidwil...@safe-mail.net wrote:
> OK I think I found my error, here is what I did:
> 
> flags = set([file for file in glob.glob('flag-*.svg')])
> 
> def call(cmd):
> subprocess.call([cmd], shell=True)

You hardly ever need shell=True. And using [cmd] is close but still not
the way. Change it to simply cmd and read on.

I would create an intermediate step creating the command you want
suprocess to run. The first 3 parts never change in your script below.

c = ['svg2png', '--width=17', '--height=12']

> for flag in flags:
> name = flag[:-4]
> out = name+'.png'

You can add a list to a list so I would write the below as.

  call(c + [flag, out])

> call('svg2png --width=17 --height=12 %s %s' \
>% (flag, out))
> 

This should make subprocess take your full command. Whether the command
is correct is another question ;-)

Greets
Sander

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread ALAN GAULD


> > What I do for these things is create a shortcut which specifies the full
> > path to the interpreter and to the pyw file. I also set the working foldeer
> > to wherever is most appropriate - usually my project folder. That's fairly
> > bulletproof in my experience!
> 
> Alan, here's what have now to call Ulipad: the shortcut shown in the
> attached image. It opens Ulipad, but a Ulipad that uses 2.51, not 2.62

So edit the Target field of the shortcut to say:

E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw

Or whatever combination of interpreter and editor you want.
In other words explicitly specify both the interpreter and the file rather than 
relying on Windows file associations.

And if that fails to work, the lasst resort is to write a batch file that calls 
the right file with the rigt interpreter and then create a shortcut to that!


> at E:\Python26\pythonw.exe (is that what you mean by the
> interpreter?).


Yes that is the interpreter.

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


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread Alan Gauld


"Chris Castillo"  wrote



and I am trying to turn it into english with the following code:

def eng2leet(astring):
   astring = astring.replace("4","a")
   astring = astring.replace("8","b")
   astring = astring.replace("[","c")
   astring = astring.replace("|)","d")


You might want to investigate the maketrans and translate 
functions in the string module.


The seem to be quite similar in intent to what you are trying 
to do?


HTH,


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

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dick Moores
On Mon, Jul 27, 2009 at 12:50, ALAN GAULD wrote:
>
>
>> > What I do for these things is create a shortcut which specifies the full
>> > path to the interpreter and to the pyw file. I also set the working foldeer
>> > to wherever is most appropriate - usually my project folder. That's fairly
>> > bulletproof in my experience!
>>
>> Alan, here's what have now to call Ulipad: the shortcut shown in the
>> attached image. It opens Ulipad, but a Ulipad that uses 2.51, not 2.62
>
> So edit the Target field of the shortcut to say:
>
> E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw

No, I'd already tried that. Doesn't work. Nothing happens.

> Or whatever combination of interpreter and editor you want.

That is the correct combination.

> In other words explicitly specify both the interpreter and the file rather 
> than
> relying on Windows file associations.
>
> And if that fails to work, the lasst resort is to write a batch file that 
> calls
> the right file with the rigt interpreter and then create a shortcut to that!

Any chance you could write that batch file for me?

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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Alan Gauld


"Dick Moores"  wrote


So edit the Target field of the shortcut to say:

E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw


No, I'd already tried that. Doesn't work. Nothing happens.


OK, You could try changing pythonw.exe tyo python.exe to
bring up a console and watch for errors there

Or just try typing the command into a console session till
you get one that works!

In other words explicitly specify both the interpreter and the file 
rather than

relying on Windows file associations.

And if that fails to work, the lasst resort is to write a batch file 
that calls
the right file with the rigt interpreter and then create a shortcut to 
that!


Any chance you could write that batch file for me?


Look at the one used for IDLE in standard python - idle.bat.

Just copy and edit it as suggested by someone earlier.

Finally, never having used ulipad, is it the interpreter called by the 
editor

that you are trying to change? Or the interpretor that runs the editor?
When you say "nothing happens" do you mean the editor doesn't start?
Or just that it still uses the wrong version of Python?

If it's the interpreter used by the editor to run programs that may be
defined in ulipad's config details somewhere - either an ini file or
in the registry.  In which case find it and edit it manually.
Or it could be by ulipad reading it from the environment - in which
case there won't be much you can do!

HTH,

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



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


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dick Moores
On Mon, Jul 27, 2009 at 14:32, Alan Gauld wrote:
>
> "Dick Moores"  wrote
>
>>> So edit the Target field of the shortcut to say:
>>>
>>> E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw
>>
>> No, I'd already tried that. Doesn't work. Nothing happens.
>
> OK, You could try changing pythonw.exe tyo python.exe to
> bring up a console and watch for errors there

I get a console for a fraction of a second. Can't read anything it says.

> Or just try typing the command into a console session till
> you get one that works!


>>> In other words explicitly specify both the interpreter and the file
>>> rather than
>>> relying on Windows file associations.
>>>
>>> And if that fails to work, the lasst resort is to write a batch file that
>>> calls
>>> the right file with the rigt interpreter and then create a shortcut to
>>> that!
>>
>> Any chance you could write that batch file for me?
>
> Look at the one used for IDLE in standard python - idle.bat.
>
> Just copy and edit it as suggested by someone earlier.

I'm not sure how to edit it. What's required for Ulipad is quite
different, I believe.

This is what I got from Dave Angel:
e:
  cd \Python26\Lib\idlelib\
  ..\..\pythonw.exe idle.pyw %*

And I can't decipher it. What is the "..\..\"?

I would like to learn how to write simple batch files, however, quite
aside from writing one to solve my Ulipad problem.

> Finally, never having used ulipad, is it the interpreter called by the
> editor
> that you are trying to change? Or the interpretor that runs the editor?

The latter, I believe.

> When you say "nothing happens" do you mean the editor doesn't start?

Yes.

> Or just that it still uses the wrong version of Python?
>
> If it's the interpreter used by the editor to run programs that may be
> defined in ulipad's config details somewhere - either an ini file or
> in the registry.  In which case find it and edit it manually.
> Or it could be by ulipad reading it from the environment - in which
> case there won't be much you can do!

I think I'll wait until the developer, who is in China (Beijing, I
believe), wakes up and gets back to his computer. It's 6:19 am there
now. If I understood him correctly, the version of Python Ulipad's
shell uses should be the same as the version of Python it uses to run
scripts inside Ulipad. But in my case, the shell runs 2.51; 2.62 runs
my scripts.

Thanks very much Alan, and everybody! If I get this solved, I'll write back.

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


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread Kent Johnson
On Mon, Jul 27, 2009 at 4:02 PM, Alan Gauld wrote:

> You might want to investigate the maketrans and translate functions in the
> string module.
>
> The seem to be quite similar in intent to what you are trying to do?

No, those will only do 1-for-1 character substitutions.

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


[Tutor] Help...

2009-07-27 Thread Ryan V
For this source code, i am getting some errors, and not sure how to fix it,
as i am returning all the values. it is telling me that there is no value
for the variables i am returning.  any help is greatly appreciated!
Source
#main function
def main():
print 'The menu is:'
print 'Yum Yum Burger for $0.99'
print 'Grease Yum Fries for $0.79'
print 'Soda Yum For $1.09'
mealOrder = input_meal()
burgerPrice = input_burger()
friesPrice = input_fries()
sodaPrice = input_soda()
mealEnd = input_mealEnd()
calc_total(burgerPrice, friesPrice, sodaPrice)
#print_info(total)

def input_meal():
print 'If you want the Yum Yum Burger please press 1'
print 'If you want the Grease Yum Fries please press 2'
print 'If you want the Soda Yum please press 3'
print 'If you entered no instead of yes just hit 4'
mealOrder = input('Enter Now - ')
if mealOrder == '1' :
input_burger()
elif mealOrder == '2' :
input_fries()
elif mealOrder == '3' :
input_soda()
elif mealOrder == '4' :
calc_total(burgerPrice, friesPrice, sodaPrice)

def input_burger():
amountBurger = input('How many burgers would you like?')
burgerPrice = amountBurger * 0.99
input_mealEnd()
return burgerPrice

def input_fries():
amountFries = input('How many Fries would you like?')
friesPrice = amountFries * 0.79
input_mealEnd()
return friesPrice

def input_soda():
amountSoda = input('How many sodas would you like?')
sodaPrice = amountSoda * 1.09
input_mealEnd()
return sodaPrice

def input_mealEnd():
mealEnd = raw_input('Would you like to end your order? (Enter yes or
no)')
if mealEnd == 'yes' :
calc_total(burgerPrice, friesPrice, sodaPrice)
elif mealEnd == 'no' :
input_meal()

#Calculation of meal cost
def calc_total(burgerPrice, friesPrice, sodaPrice):
totalFood = burgerPrice + friesPrice + sodaPrice
totalTax = totalFood * .06
total = totalTax + totalFood
print 'The total price for food is $', totalFood
print 'The Tax is $', totalTax
print 'The total is $', total
#Displays total, and what you ordered
#def print_info(total):
#print 'The meal price is $', total

#call main function
main()
 and here is the output i am getting

The menu is:
Yum Yum Burger for $0.99
Grease Yum Fries for $0.79
Soda Yum For $1.09
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 1
How many burgers would you like?2
Would you like to end your order? (Enter yes or no)no
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 2
How many Fries would you like?2
Would you like to end your order? (Enter yes or no)no
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 3
How many sodas would you like?2
Would you like to end your order? (Enter yes or no)yes
*Traceback (most recent call last):
  File "...", line 74, in 
main()
  File "...", line 16, in main
sodaPrice = input_soda()
  File "...", line 51, in input_soda
input_mealEnd()
  File "...", line 57, in input_mealEnd
calc_total(burgerPrice, friesPrice, sodaPrice)
NameError: global name 'burgerPrice' is not defined*
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Eng to Leet Speek

2009-07-27 Thread bob gailer

Kent Johnson wrote:

On Mon, Jul 27, 2009 at 4:02 PM, Alan Gauld wrote:

  

You might want to investigate the maketrans and translate functions in the
string module.

The seem to be quite similar in intent to what you are trying to do?



No, those will only do 1-for-1 character substitutions.


Which could be applied to all the 1 character substitutions after 
dealing with the multi-character ones.


--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Getting Data from a Web Page

2009-07-27 Thread Paras K.
First let me say this mailing list is GREAT!!! Has helped me out through
many things.

I have written some code with Python that currently goes through a directory
of all csv files and pulls out the lines that are needed by this program.

These csv files have the following information:

IP Address, Activity, Count, Date

Currently the code looks at the IP address and if it is part of the range
overall range then it writes it to a new csv file.

I have two things that I would like to improve on:

1) If the IP address falls within a specific range I want it to add an
indicator at the end of it like -- NONDHCP IP
(I believe I know how to do this, but any suggestion would be great)

2) If the IP is a DHCP IP -- I want it to be able to get the data from a
webpage -- this webpage has like user information and etc.
Is there any way to do that?

Thank You for all your help in advance!!!


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


[Tutor] self.name vs. passing a name

2009-07-27 Thread Che M

This is another very basic structural question, related to one I asked last 
week, and again is not necessarily germane only to Python.

Let's say you have a sequence of two calculations or manipulations you need to 
do, each one done as a function called by an overall calculate_something() 
function.  The "answer" to each function is then used in the next function.  I 
can think of two ways to make that answer available for use in the next 
function:  1) pass it in, or 2) declare it as self.answer and then it is 
available to the whole class instance.

What are the dis/advantages to these two different ways?  Here are examples, 
with only the overall calculate_something() function shown:

1.Pass the variable to the second function.

def calculate_something(self):
answer = self.do_first_calculation()#1st function returns answer
self.do_second_calculation(answer)#2nd is passed answer and uses it.

2. Create the variable in the class instance scope and use that in the second 
function.

def calculate_something(self):

self.do_first_calculation() #1st function creates 
self.answer

self.do_second_calculation() #2nd uses self.answer

Both of these approaches can work, but I would like to better understand when 
it is best to do one or the other.  Obviously if I know I will need to make 
self.answer available for use by other functions, I would want to choose (2).  
But what other considerations should I, well, consider?

Thanks,
Che





_
NEW mobile Hotmail. Optimized for YOUR phone.  Click here.
http://windowslive.com/Mobile?ocid=TXT_TAGLM_WL_CS_MB_new_hotmail_072009___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread ALAN GAULD


> I get a console for a fraction of a second. Can't read anything it says.
> 
> > Or just try typing the command into a console session till
> > you get one that works!
> 


So what happens when you run the same command from a console?
That should leave the errors visible.

> I'm not sure how to edit it. What's required for Ulipad is quite
> different, I believe.


It shouldn't be, it just calls the interpreter with the pyw file to launch 
the editor and passes along any other command line arguments 
given to the bat file.

> This is what I got from Dave Angel:
> e:
>   cd \Python26\Lib\idlelib\
>   ..\..\pythonw.exe idle.pyw %*
> 
> And I can't decipher it. What is the "..\..\"?


.. means the folder one level up,
so ..\..\pythonw.exe means backup two levelsand call pythonw.exe there

> I would like to learn how to write simple batch files, however, quite
> aside from writing one to solve my Ulipad problem.


It is a useful skill.

> > that you are trying to change? Or the interpretor that runs the editor?
> 
> The latter, I believe.


OK, thats what I initially thought, but then wondered...

> > When you say "nothing happens" do you mean the editor doesn't start?
> 
> Yes.


I'd definitely try running from a command prompt.

> I think I'll wait until the developer, who is in China (Beijing, I
> believe), wakes up and gets back to his computer. 

That might be best :-)

> now. If I understood him correctly, the version of Python Ulipad's
> shell uses should be the same as the version of Python it uses to run
> scripts inside Ulipad. But in my case, the shell runs 2.51; 2.62 runs
> my scripts.


Now I'm confused again. What do you mean by the shell?
Does Ulipad have a shell window like IDLE? If so it is almost certainly 
using the same interpreter as is running the editor itself (because the 
shell is probavbly using exec() ) The version of Python used to run 
your scripts could be anything however.


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


Re: [Tutor] self.name vs. passing a name

2009-07-27 Thread Kent Johnson
On Mon, Jul 27, 2009 at 7:39 PM, Che M wrote:
> 1.Pass the variable to the second function.
>
> def calculate_something(self):
>     answer = self.do_first_calculation()    #1st function returns answer
>     self.do_second_calculation(answer)    #2nd is passed answer and uses it.
>
> 2. Create the variable in the class instance scope and use that in the
> second function.
>
> def calculate_something(self):
>     self.do_first_calculation() #1st function creates
> self.answer
>     self.do_second_calculation() #2nd uses self.answer
>
> Both of these approaches can work, but I would like to better understand
> when it is best to do one or the other.

i would use the first method.
- it makes explicit that do_first_calculation() is computing something
needed by the second
- you could give the variable a better name which would make it easier
to understand calculate_something()
- answer is not part of the state of self and it has no meaning
outside of calculate_something(), so don't clutter up self with the
extra value.

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


Re: [Tutor] [Baypiggies] Egnyte: hiring

2009-07-27 Thread mobiledreamers
Seems interesting
http://fotoroll.com/searchvideo?q=vineet%20jain,%20ceo%20of%20egnyte&id=0&type=video



On Mon, Jul 27, 2009 at 7:46 PM, Aahz  wrote:

> My new company (I just started today) closed a big venture capital round
> (also today) and is looking to hire more people, preferably with Python
> experience:
>
> Senior Linux Engineer:
> http://sfbay.craigslist.org/pen/sof/1292008176.html
>
> Senior Platforms Engineer:
> http://sfbay.craigslist.org/pen/sof/1291776907.html
>
> Venture announcement:
> http://blogs.zdnet.com/BTL/?p=21777
>
> I can't say a lot about the company myself yet, but I've gotten a good
> impression of the team and the business plan.  Find out more here:
> http://www.egnyte.com/
> --
> Aahz (a...@pythoncraft.com)   <*>
> http://www.pythoncraft.com/
>
> "Many customs in this life persist because they ease friction and promote
> productivity as a result of universal agreement, and whether they are
> precisely the optimal choices is much less important." --Henry Spencer
> ___
> Baypiggies mailing list
> baypigg...@python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>



-- 
Bidegg worlds best auction site
http://bidegg.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] No Elegant XML Output in ElementTree?

2009-07-27 Thread Luis Galvan
Hi tutors,
Okay, so I just started to learn ElementTree (and XML processing in general)
and I just can't, for the life of me, find a way to output the XML file in
an actual hierarchic presentation.  What I mean by this is that it all
outputs on a single line.  For example, I create an element tree in python:


from xml.etree.ElementTree import ElementTree, SubElement, Element

# Create example tree.
root = Element("BFTypedBinder")
root.set("binderType", "codename")

# There's no point in this loop, it's only here for kicks.
while True:
x = raw_input("Yes or No?  ")
if x == "Yes":
head = SubElement(root, "sample")

title = SubElement(head, "sample2")
title.text = "Sample Text"

body = SubElement(root, "sample3")
body.set("this", "that")

body.text = "Done"
break
elif x == "No":
break

# Save output.
tree = ElementTree(root)
tree.write(xml.xml)

___
Output using Notepad:
Sample
TextDone


If I open xml.xml in Notepad, the whole tree is printed on one line, which
isn't what I want.  Of course, if I double click the file itself, it looks
normal, but I still need the data itself to look hierarchic as well (It's a
personal preference, and much more convenient when editing in a text
editor).  A few months back when I was attempting to learn Minidom, it
didn't have this problem.  I have looked through python.org's online
documentation on ET and there's no method, class, or function that could
help me achieve this, at least that I'm aware of.

I know I might have to write a solution myself, but before I try (which
would probably be disasterous), is there some existing built-in class in
here that can help me without having to "reinvent the wheel"?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No Elegant XML Output in ElementTree?

2009-07-27 Thread Marc Tompkins
On Mon, Jul 27, 2009 at 8:32 PM, Luis Galvan wrote:

> Hi tutors,
> Okay, so I just started to learn ElementTree (and XML processing in
> general) and I just can't, for the life of me, find a way to output the XML
> file in an actual hierarchic presentation.


What you want is generically called "prettyprinting".  I don't use
ElementTree myself (I use Amara/Akara), so I don't know whether effbot
followed through on this, but take a look at this page:
http://effbot.org/zone/element-lib.htm

I also found this page:
http://renesd.blogspot.com/2007/05/pretty-print-xml-with-python.html
and in the comments there's this, which looks pretty simple:

To pretty print an ElementTree:

from xml.minidom import parseString
from xml.etree import ElementTree

def prettyPrint(element):
txt = ElementTree.tostring(element)
print minidom.parseString(txt).toprettyxml()
Substitute output to a file for "print", and you're done.In Amara, I do
this:
def Save(self):
outFile = open(self.fileName,'w+b')
self.xDoc.xml(outFile,indent=u'yes')
outFile.close()
but that's not much help for etree, I know...

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


Re: [Tutor] Help...

2009-07-27 Thread Christian Witts

Ryan V wrote:
For this source code, i am getting some errors, and not sure how to 
fix it, as i am returning all the values. it is telling me that there 
is no value for the variables i am returning.  any help is greatly 
appreciated!

Source
#main function
def main():
print 'The menu is:'
print 'Yum Yum Burger for $0.99'
print 'Grease Yum Fries for $0.79'
print 'Soda Yum For $1.09'
mealOrder = input_meal()
burgerPrice = input_burger()
friesPrice = input_fries()
sodaPrice = input_soda()
mealEnd = input_mealEnd()
calc_total(burgerPrice, friesPrice, sodaPrice)
#print_info(total)

def input_meal():
print 'If you want the Yum Yum Burger please press 1'
print 'If you want the Grease Yum Fries please press 2'
print 'If you want the Soda Yum please press 3'
print 'If you entered no instead of yes just hit 4'
mealOrder = input('Enter Now - ')
if mealOrder == '1' :
input_burger()
elif mealOrder == '2' :
input_fries()
elif mealOrder == '3' :
input_soda()
elif mealOrder == '4' :
calc_total(burgerPrice, friesPrice, sodaPrice)
   
def input_burger():

amountBurger = input('How many burgers would you like?')
burgerPrice = amountBurger * 0.99
input_mealEnd()
return burgerPrice
   
def input_fries():

amountFries = input('How many Fries would you like?')
friesPrice = amountFries * 0.79
input_mealEnd()
return friesPrice
   
def input_soda():

amountSoda = input('How many sodas would you like?')
sodaPrice = amountSoda * 1.09
input_mealEnd()
return sodaPrice
   
def input_mealEnd():
mealEnd = raw_input('Would you like to end your order? (Enter yes 
or no)')

if mealEnd == 'yes' :
calc_total(burgerPrice, friesPrice, sodaPrice)
elif mealEnd == 'no' :
input_meal()

#Calculation of meal cost
def calc_total(burgerPrice, friesPrice, sodaPrice):
totalFood = burgerPrice + friesPrice + sodaPrice
totalTax = totalFood * .06
total = totalTax + totalFood
print 'The total price for food is $', totalFood
print 'The Tax is $', totalTax
print 'The total is $', total
#Displays total, and what you ordered
#def print_info(total):
#print 'The meal price is $', total

#call main function
main()
 and here is the output i am getting

The menu is:
Yum Yum Burger for $0.99
Grease Yum Fries for $0.79
Soda Yum For $1.09
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 1
How many burgers would you like?2
Would you like to end your order? (Enter yes or no)no
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 2
How many Fries would you like?2
Would you like to end your order? (Enter yes or no)no
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 3
How many sodas would you like?2
Would you like to end your order? (Enter yes or no)yes
*Traceback (most recent call last):
  File "...", line 74, in 
main()
  File "...", line 16, in main
sodaPrice = input_soda()
  File "...", line 51, in input_soda
input_mealEnd()
  File "...", line 57, in input_mealEnd
calc_total(burgerPrice, friesPrice, sodaPrice)
NameError: global name 'burgerPrice' is not defined*


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  
You're caliing calc_total() in your input_mealEnd() function and in the 
scope of that function there are no variables names burgerPrice, 
friesPrice or sodaPrice.


--
Kind Regards,
Christian Witts


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