Re: [Tutor] Exercises for Classes and OOP in Python

2009-02-23 Thread Alan Gauld
"Senthil Kumaran"  wrote 


I am looking for a good material that would provide exercises  (and
possibly solutions to demo exercises) that illustrates the Object
Oriented Programming constructs in Python.  Can pointers?


I'm not sure what exactly you have in mind but most tutorials 
will cover OOP and you can generally take their examples 
and expand them in different ways to explore the features. 
Similarly most software problems can have an OOP solution 
so you could simply find OOP altrernatives to exercises you 
have already done in a non OOP way.


Or ar you looking for something along the line of:

1) define a Shape class

2) define a circle square and triange from the shape

3) add a class attribute to your shape class

4) use polymorphic methods to embellish your shape classes

etc?

Those kinds of exercises are easy enough to invent yourself. 
And other than practicing the syntax won't help much in real-world 
type scenarios.  IMHO


HTH,

Alan G.

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


Re: [Tutor] regex help

2009-02-23 Thread Alan Gauld
"ish_ling"  wrote 


   'a b c h'

I would like a regex to 


Congratulations on a cclear explanation of what you want. 
With regex questions that is half the battle.



I have figured out how to do this in a multiple-step process


And there's nothing much wrong with multi step.

with re.findall() in order to find two strings 


   ['d e f ', 'i j ']

I can then use another regex to extract the letters 


But you don't need a regex to do that, it could be a list 
comprehension:


[ch for s in yourList for ch in s if ch != ' ' ]


HTH,


--
Alan G
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] extracting a column from many files

2009-02-23 Thread Bala subramanian
>
>
> file1:
> 1a1 1b1 1c1 1d1 1e1 1f1
> 2a1 2b1 2c1 2d1 2e1 2f1
> 3a1 3b1 3c1 3d1 3e1 3f1
>
> file2:
> 1a2 1b2 1c2 1d2 1e2 1f2
> 2a2 2b2 2c2 2d2 2e2 2f2
> 3a2 3b2 3c2 3d2 3e2 3f2
>
> How do you want the output files to look like?
>

I want to extract  1a1 2a1 3a1 from file 1, similarly 1a2 2a2 3a2 from file
2 ( same columns) and then make a new output file of the following format

1a1 1a2 ---
2a1 2a2 ---
3a1 3a2 ---

Similarly for the 2nd, 3rd, 4th..columns in the input files.

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


Re: [Tutor] regex help

2009-02-23 Thread Paul McGuire
I second Alan G's appreciation for a well-thought-through and well-conveyed
description of your text processing task.  (Is "Alan G" his gangsta name, I
wonder?)

This pyparsing snippet may point you to some easier-to-follow code,
especially once you go beyond the immediate task and do more exhaustive
parsing of your syllable syntax.


from pyparsing import *

LT,GT = map(Suppress,"<>")
lower = oneOf(list(alphas.lower()))
H = Suppress("H")

# have to look ahead to only accept lowers if NOT followed by H
patt = LT + H + ZeroOrMore(lower + ~H)("body")  + lower + H + GT

tests = """\
a b c h
a b c
a b c""".splitlines()

for t in tests:
print t
print sum((list(p.body)
for p in patt.searchString(t) if p.body), [])
print

Prints:

a b c h
['d', 'e', 'f', 'i', 'j']

a b c
[]

a b c
['d']

There is more info on pyparsing at http://pyparsing.wikispaces.com.

-- Paul



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


Re: [Tutor] regex help

2009-02-23 Thread Kent Johnson
On Sun, Feb 22, 2009 at 10:49 PM, ish_ling  wrote:
> I have a string:
>
>'a b c h'
>
> I would like a regex to recursively match all alpha letters that are between 
> . That is, I would like the following list of matches:
>
>['d', 'e', 'f', 'i', 'j']
>
> I do not want the 'g' or the 'k' matched.
>
> I have figured out how to do this in a multiple-step process, but I would 
> like to do it in one step using only one regex (if possible). My multiple 
> step process is first to use the regex
>
>'(?<=H )[a-z][^H]+(?!H)'

I would use a slightly different regex, it seems more explicit to me.
r''
>
> with re.findall() in order to find two strings
>
>['d e f ', 'i j ']
>
> I can then use another regex to extract the letters out of the strings.

str.split() will pull out the individual strings. You can still write
it as a one-liner if you want:

In [1]: import re

In [2]: s = 'a b c h'

In [3]: regex = r''

In [5]: [m.split() for m in re.findall(regex, s)]
Out[5]: [['d', 'e', 'f'], ['i', 'j']]

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


Re: [Tutor] regex help

2009-02-23 Thread spir
Le Mon, 23 Feb 2009 06:45:23 -0500,
Kent Johnson  s'exprima ainsi:

> On Sun, Feb 22, 2009 at 10:49 PM, ish_ling  wrote:
> > I have a string:
> >
> >'a b c h'
> >
> > I would like a regex to recursively match all alpha letters that are
> > between . That is, I would like the following list of
> > matches:
> >
> >['d', 'e', 'f', 'i', 'j']
> >
> > I do not want the 'g' or the 'k' matched.
> >
> > I have figured out how to do this in a multiple-step process, but I would
> > like to do it in one step using only one regex (if possible). My multiple
> > step process is first to use the regex
> >
> >'(?<=H )[a-z][^H]+(?!H)'
> 
> I would use a slightly different regex, it seems more explicit to me.
> r''

You can even probably exclude leading & trailing spaces from match:
r''
returns
['d e f', 'i j']


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


--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] create dictionary from csv data

2009-02-23 Thread Norman Khine

Hello,

I have this csv file:

$ cat licences.csv
"1","Air Travel Organisation Licence (ATOL)\n Operates Inclusive Tours (IT)"
"2","Air Travel Organisation Licence (ATOL)\n Appointed Agents of IATA 
(IATA)"

"3", "Association of British Travel Agents (ABTA) No. 56542\n Air Travel
Organisation Licence (ATOL)\n Appointed Agents of IATA (IATA)\n 
Incentive Travel & Meet. Association (ITMA)"


I would like to create a set of unique values for all the memberships. i.e.

ATOL
IT
ABTA
etc..

and also I would like to extract the No. 56542

and lastly I would like to map each record to the set of unique 
membership values, so that:


I have a dictionary like:

{0: ['1', '('ATOL', 'IT')'],
1: ['2','('ATOL', 'IATA')'],
2: ['3','('ABTA', 'ATOL', 'IATA', 'ITMA')']}

Here is what I have so far:

>>> import csv
>>> inputFile = open(str("licences.csv"),  'r')
>>> outputDic = {}
>>> keyIndex = 0
>>> fileReader = csv.reader(inputFile)
>>> for line in fileReader:
... outputDic[keyIndex] = line
... keyIndex+=1
...
>>> print outputDic
{0: ['2', 'Air Travel Organisation Licence (ATOL) Appointed Agents of 
IATA (IATA)'], 1: ['3', ' "Association of British Travel Agents (ABTA) 
No. 56542 Air Travel'], 2: ['Organisation Licence (ATOL) Appointed 
Agents of IATA (IATA) Incentive Travel & Meet. Association (ITMA)"']}


So basically I would like to keep only the data in the brackets, i.e. 
(ABTA) etc..


Cheers

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


Re: [Tutor] Simple CGI script and Apache configuration

2009-02-23 Thread wormwood_3
Well that did seem to help, at least I get an error now:-)

I changed my config to:

ScriptAlias /python/ /var/www/samuelhuckins.com/python/


SetHandler mod_python
PythonHandler mod_python.publisher
PythonDebug On


So I have the / as mentioned on ScriptAlias, and I added what seems to be the 
lines suggested in all the tutorials I came across. Now when you hit 
http://trac.samuelhuckins.com/python/hello.py, you get:

Environment not foundWhen I hit the script on the command line, I get back what 
I think should display fine:

./hello.py
Content-type: text/html


Hello!


I don't see anything in the Apache error logs. Any ideas?

-Sam

 ___
Samuel Huckins


Homepage - http://samuelhuckins.com
Tech blog - http://dancingpenguinsoflight.com/
Photos - http://www.flickr.com/photos/samuelhuckins/
AIM - samushack | Gtalk - samushack | Skype - shuckins





From: Moos Heintzen 
To: wormwood_3 
Sent: Sunday, February 22, 2009 5:36:32 PM
Subject: Re: [Tutor] Simple CGI script and Apache configuration

Just noticed that

ScriptAlias /python/ "/var/www/samuelhuckins.com/python"

doesn't have a slash at the end. Could that be it?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create dictionary from csv data

2009-02-23 Thread spir
Le Mon, 23 Feb 2009 14:41:10 +0100,
Norman Khine  s'exprima ainsi:

> Hello,
> 
> I have this csv file:
> 
> $ cat licences.csv
> "1","Air Travel Organisation Licence (ATOL)\n Operates Inclusive Tours (IT)"
> "2","Air Travel Organisation Licence (ATOL)\n Appointed Agents of IATA 
> (IATA)"
> "3", "Association of British Travel Agents (ABTA) No. 56542\n Air Travel
> Organisation Licence (ATOL)\n Appointed Agents of IATA (IATA)\n 
> Incentive Travel & Meet. Association (ITMA)"

I have the impression that the CSV module is here helpless. Yes, it parses the 
data, but you need only a subset of it that may be harder to extract. I would 
do the following (all untested):

-0- Read in the file as a single string.

> I would like to create a set of unique values for all the memberships. i.e.
> 
> ATOL
> IT
> ABTA
> etc..

-1- Use re.findall with a pattern like r'\((\w+)\)' to get the company codes, 
then built a set out of the result list

> and also I would like to extract the No. 56542

-2- idem, with r'No. (\d+)' (maybe set is not necessary)

> and lastly I would like to map each record to the set of unique 
> membership values, so that:
> 
> I have a dictionary like:
> 
> {0: ['1', '('ATOL', 'IT')'],
> 1: ['2','('ATOL', 'IATA')'],
> 2: ['3','('ABTA', 'ATOL', 'IATA', 'ITMA')']}

(The dict looks strange...)

-3- Now "splitlines" the string, and on each line
* read ordinal number (maybe useless actually)
* read again the codes
I dont know what your dict is worthful for, as the keys are simple ordinals. 
It's a masked list, actually. Unless you want instead
{['1':['ATOL', 'IT'],
'2':['ATOL', 'IATA'],
'3':['ABTA', 'ATOL', 'IATA', 'ITMA']}
But here the keys are still predictable ordinals.

denis
--
la vita e estrany

> Here is what I have so far:
> 
>  >>> import csv
>  >>> inputFile = open(str("licences.csv"),  'r')
>  >>> outputDic = {}
>  >>> keyIndex = 0
>  >>> fileReader = csv.reader(inputFile)
>  >>> for line in fileReader:
> ... outputDic[keyIndex] = line
> ... keyIndex+=1
> ...
>  >>> print outputDic
> {0: ['2', 'Air Travel Organisation Licence (ATOL) Appointed Agents of 
> IATA (IATA)'], 1: ['3', ' "Association of British Travel Agents (ABTA) 
> No. 56542 Air Travel'], 2: ['Organisation Licence (ATOL) Appointed 
> Agents of IATA (IATA) Incentive Travel & Meet. Association (ITMA)"']}
> 
> So basically I would like to keep only the data in the brackets, i.e. 
> (ABTA) etc..
> 
> Cheers
> 
> Norman
> ___
> 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] Looking for ConfigObj Documentation

2009-02-23 Thread ALAN GAULD
> Under Start there's a ? icon that says Help and Support.  Minimal info. 

Yes, although by exploring the links and using the Microsoft Knowledgebase 
panel on the left you do get more than I remembered. I just think the DOS 
HELP command is easier to use.

However I did find a good overview on Technet:

http://technet.microsoft.com/en-us/library/bb490954.aspx

Which has a lot of other stuff on cmd.exe too.

> It seems to me that the Command Prompt window is important enough 
> in
the use of Python to warrant a full page somewhere to its
applicability. 

I might try to do that sometime. But its not really Python specific, if you 
are doing any serious programming or admin work on a PC you really 
should be familiar with the cmd window, its often the fastest and easiest 
way to do stuff. And learning the little tricks and settings that make it 
more productive is definitely worthwhile.

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


Re: [Tutor] extracting a column from many files

2009-02-23 Thread Alan Gauld


"Bala subramanian"  wrote

I want to extract  1a1 2a1 3a1 from file 1, similarly 1a2 2a2 3a2 
from file
2 ( same columns) and then make a new output file of the following 
format


1a1 1a2 ---
2a1 2a2 ---
3a1 3a2 ---

Similarly for the 2nd, 3rd, 4th..columns in the input files.


OK, So you want separate output files per column?
And each file contains the same column from each
of the input files?

So
output1.txt contains all of the column 1 data
output2.txt contains all of the column 2 data
and so on?

Alan G 



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


Re: [Tutor] extracting a column from many files

2009-02-23 Thread Moos Heintzen
Here's a simple repositioning code given that you already have the
fields extracted.
All files have to have equal dimensions.

file1 = [["1a1", "1b1", "1c1",], ["2a1", "2b1", "2c1"],]
file2 = [["1a2", "1b2", "1c2",], ["2a2", "2b2", "2c2"],]
files = [file1, file2]
out_lines = []

for column in range(len(files[0][0])):
   for fileno in range(len(files)):
   out_lines.append([])
   for row in range(len(files[0])):
   out_lines[-1].append(files[fileno][row][column])
   # write out_lines to file "file%s" % column
   print out_lines
   out_lines = []

No offense, but your extracting code looks a bit inflexible. It has a
lot of magic numbers, and most of it is hardcoded.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple CGI script and Apache configuration

2009-02-23 Thread Martin Walsh
wormwood_3 wrote:
> Hello all,

Hi Sam,

> I'll try to give as much detail as I can, but this is a somewhat vague
> problem. I have a very simple script that I would like to implement as a
> CGI script, just so I can hit a URL and get some output. However, after
> following a number of tutorials, I am still seeing some very odd
> results. I am almost sure it's in my Apache configuration, but I figured
> a few people on this list would likely know what the minimal related
> Apache config should be. (The Apache docs are pretty daunting...)
> 
> Local version wise, I am on Ubuntu 8.10, with Apache 2.2.9 and Python
> 2.5.2. I have libapache2-mod-python installed. Apache config is out of
> the box, along with:
> 
> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

You need more than this to make apache cgi work, I think.

Firstly, mod_cgi should be loaded -- look for a symlink named cgi.load
or some such, in /etc/apache2/mods-enabled. Run 'a2enmod cgi' if you
don't have one. Secondly, ExecCGI is usually enabled using the Options
directive within a Directory definition -- but, less commonly, you might
see something like 'AddHandler cgi-program .py' in an apache or site
config.

Of course, the script needs to be executable by the apache user (which
would be 'www-data' on ubuntu, IIRC), and contain an appropriate shebang
(#!) on the first line -- but it sounds like you have that covered.

Both 'Options ExecCGI' and 'Addhandler cgi-program .py' are allowed in
.htaccess also, given an appropriate AllowOverride directive for the
path in question. Something to look for on the working system, if all
else fails.

You do *not* need mod python to run python cgi scripts.

> In /var/www/cgi-bin, I have hello.py :
> 
> #!/usr/bin/python
> import cgitb
> cgitb.enable()
> 
> print "Content-type: text/html"
> print
> print ""
> print "Hello!"
> print ""
> 
> Reload, hit http://localhost/cgi-bin/hello.py in a browser, I get
> centered text just fine. Now I want to do this same process on my remote
> webserver. On there, I am on Ubuntu 7.10, with Apache 2.2.4 and Python
> 2.5.1. I add:
> 
> ScriptAlias /python/ "/var/www/samuelhuckins.com/python"

You can try appending something like this (untested):


  AllowOverride None
  Options ExecCGI
  # or, Options +ExecCGI to merge
  # with options from parent dir(s)
  Order allow,deny
  Allow from all


> 
> Reload, hit http://samuelhuckins.com/python/hello.py, and I get a 404?
> The perms and ownership on the file is the same as in other directories.
> Do I need to add some sort of handler, with mod_python.publisher? I
> think I am just missing one of the basics of this whole process.

Hmmm, interesting. It's unlikely that any of my advice will help you
with a 404. With an incomplete apache cgi config, the response I'd
expect would be either a 403 (Forbidden), or the script itself in plain
text. Do the logs provide any additional information?

Re-check your spelling. A 404 with vanilla apache config might just
indicate a typo. When you say 'Reload', I assume you mean the apache
daemon (ie. /etc/init.d/apache2 reload or apache2ctl reload)?

Again, you do *not* need mod python to run python cgi scripts.

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


Re: [Tutor] Simple CGI script and Apache configuration

2009-02-23 Thread wormwood_3
Thanks for all the suggestions! I tried to go through them, and will relate 
what results I encountered. I changed my Apache config to:

 
 AllowOverride None
 Options ExecCGI
 Order allow,deny
 Allow from all
 

I in fact did not have the cgi module enabled, so I did that. Then I ran "sudo 
/etc/init.d/apache2 reload", and hit http://samuelhuckins.com/cgi-bin/hello.py, 
which contains simply:

#!/usr/bin/python
print "Content-type: text/html"
print
print ""
print "Hello!"
print ""

I get prompted to download the file, but it does not execute or appear in plain 
text. The logs just show the request being made. What is the missing element to 
get this script to execute?

Thanks,
Sam




From: Martin Walsh 
To: Python Tutorlist 
Sent: Tuesday, February 24, 2009 12:33:35 AM
Subject: Re: [Tutor] Simple CGI script and Apache configuration

wormwood_3 wrote:
> Hello all,

Hi Sam,

> I'll try to give as much detail as I can, but this is a somewhat vague
> problem. I have a very simple script that I would like to implement as a
> CGI script, just so I can hit a URL and get some output. However, after
> following a number of tutorials, I am still seeing some very odd
> results. I am almost sure it's in my Apache configuration, but I figured
> a few people on this list would likely know what the minimal related
> Apache config should be. (The Apache docs are pretty daunting...)
> 
> Local version wise, I am on Ubuntu 8.10, with Apache 2.2.9 and Python
> 2.5.2. I have libapache2-mod-python installed. Apache config is out of
> the box, along with:
> 
> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

You need more than this to make apache cgi work, I think.

Firstly, mod_cgi should be loaded -- look for a symlink named cgi.load
or some such, in /etc/apache2/mods-enabled. Run 'a2enmod cgi' if you
don't have one. Secondly, ExecCGI is usually enabled using the Options
directive within a Directory definition -- but, less commonly, you might
see something like 'AddHandler cgi-program .py' in an apache or site
config.

Of course, the script needs to be executable by the apache user (which
would be 'www-data' on ubuntu, IIRC), and contain an appropriate shebang
(#!) on the first line -- but it sounds like you have that covered.

Both 'Options ExecCGI' and 'Addhandler cgi-program .py' are allowed in
.htaccess also, given an appropriate AllowOverride directive for the
path in question. Something to look for on the working system, if all
else fails.

You do *not* need mod python to run python cgi scripts.

> In /var/www/cgi-bin, I have hello.py :
> 
> #!/usr/bin/python
> import cgitb
> cgitb.enable()
> 
> print "Content-type: text/html"
> print
> print ""
> print "Hello!"
> print ""
> 
> Reload, hit http://localhost/cgi-bin/hello.py in a browser, I get
> centered text just fine. Now I want to do this same process on my remote
> webserver. On there, I am on Ubuntu 7.10, with Apache 2.2.4 and Python
> 2.5.1. I add:
> 
> ScriptAlias /python/ "/var/www/samuelhuckins.com/python"

You can try appending something like this (untested):


  AllowOverride None
  Options ExecCGI
  # or, Options +ExecCGI to merge
  # with options from parent dir(s)
  Order allow,deny
  Allow from all


> 
> Reload, hit http://samuelhuckins.com/python/hello.py, and I get a 404?
> The perms and ownership on the file is the same as in other directories.
> Do I need to add some sort of handler, with mod_python.publisher? I
> think I am just missing one of the basics of this whole process.

Hmmm, interesting. It's unlikely that any of my advice will help you
with a 404. With an incomplete apache cgi config, the response I'd
expect would be either a 403 (Forbidden), or the script itself in plain
text. Do the logs provide any additional information?

Re-check your spelling. A 404 with vanilla apache config might just
indicate a typo. When you say 'Reload', I assume you mean the apache
daemon (ie. /etc/init.d/apache2 reload or apache2ctl reload)?

Again, you do *not* need mod python to run python cgi scripts.

HTH,
Marty
___
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] Simple CGI script and Apache configuration

2009-02-23 Thread Martin Walsh
wormwood_3 wrote:
> Thanks for all the suggestions! I tried to go through them, and will
> relate what results I encountered. I changed my Apache config to:
> 
>  
>  AllowOverride None
>  Options ExecCGI
>  Order allow,deny
>  Allow from all
>  
> 
> I in fact did not have the cgi module enabled, so I did that. Then I ran
> "sudo /etc/init.d/apache2 reload", and hit
> http://samuelhuckins.com/cgi-bin/hello.py, which contains simply:
> 
> #!/usr/bin/python
> print "Content-type: text/html"
> print
> print ""
> print "Hello!"
> print ""
> 
> I get prompted to download the file, but it does not execute or appear
> in plain text. The logs just show the request being made. What is the
> missing element to get this script to execute?
> 

When you look at the downloaded file, is it your python script?

Looks like you changed the path where you're keeping your cgi script,
did you update the ScriptAlias directive to suit?

You may find this more helpful ...
http://httpd.apache.org/docs/2.0/howto/cgi.html

HTH,
Marty

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