Re: [Tutor] iterating in the same line

2005-08-14 Thread Alan G
Sorry Jonas,

I don't understand what you are trying to do at all.
The subject line and your code snippets don't seem 
to match up.

> Subject: [Tutor] iterating in the same line

>I would check 3 words at the starting of a line
> 
> s=['foo','bar','qwe']
> 
> if ln.startswith(s):   (this is bad)

Why is it bad -- other than it doesn't work!
I think you mean something like

for st in s:
  if line.startswith(st):  do something

> if max(map(ln.startswith,s)):

But this does something completely different!

This selects the 'biggest' line that starts with anything in s.
then if the biggest line is not null does something?

> reduce(lambda m,n:m or n, map(ln.startswith, s))

And this does something different again.
It uses map to create a list containg ln if ln startswith 
one of the strings in s, then tries to reduce that list 
to one element(which it already is!) by 'or'ing the elements.

I can't even begin to guess from that what it is you are 
actually trying to do.

Can you give us more explanation and maybe some sample data?

Alan G.

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


Re: [Tutor] Invoking bash from within a python program

2005-08-14 Thread Alan G
> Also, if you have a recent version of Python (Python 2.4), the
> 'subprocess' module might be worth a look:
> 
>http://www.python.org/doc/lib/module-subprocess.html
> 

Is it just me or does anyone else think the new subprocess module
is making something fairly easy into something fairly complicated?
There are an awful lot of options to the Popen call...

subprocess looks like the classic example of trying to rationalise 
many simple things into one and in the process making it much more 
complicated.

But I'm not using 2.4 yet so can only go by the module documentation.
How has it been in practice?

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


Re: [Tutor] Sorting a list of lists aka nested lists

2005-08-14 Thread Alan G
>Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 
> 0, 0 ] )
>
> After Quant is created, I want to sort it by MTD.  If I use a simple 
> Quant.sort(), I assume its going to sort by 'db_ticker' which is not 
> what I want.

you need to write your own comparison function.
Basically it will take two of your lists and return -1,0 or 1.

Or you can use Python's own logic to help

def cmplists(lst1,lst2):
   return cmp(lst1[2],lst2[2])

Now you can sort Quant by passing your function into sort...

HTH,

Alan G. 

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


Re: [Tutor] iterating in the same line

2005-08-14 Thread Jonas Melian
I'm trying match the lines that starting with someone variable in 's'

These sentences:
if max(map(ln.startswith,s)):
reduce(lambda m,n:m or n, map(ln.startswith, s)):

were said me in #python for this proposal.


Alan G wrote:

> Sorry Jonas,
>
> I don't understand what you are trying to do at all.
> The subject line and your code snippets don't seem to match up.
>
>> Subject: [Tutor] iterating in the same line
>
>
>> I would check 3 words at the starting of a line
>>
>> s=['foo','bar','qwe']
>>
>> if ln.startswith(s):   (this is bad)
>
>
> Why is it bad -- other than it doesn't work!
> I think you mean something like
>
> for st in s:
>  if line.startswith(st):  do something
>
>> if max(map(ln.startswith,s)):
>
>
> But this does something completely different!
>
> This selects the 'biggest' line that starts with anything in s.
> then if the biggest line is not null does something?
>
>> reduce(lambda m,n:m or n, map(ln.startswith, s))
>
>
> And this does something different again.
> It uses map to create a list containg ln if ln startswith one of the 
> strings in s, then tries to reduce that list to one element(which it 
> already is!) by 'or'ing the elements.
>
> I can't even begin to guess from that what it is you are actually 
> trying to do.
>
> Can you give us more explanation and maybe some sample data?
>
> Alan G.
>
>

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


Re: [Tutor] iterating in the same line

2005-08-14 Thread Alan G

> I'm trying match the lines that starting with someone variable in 
> 's'

In that case this is the simplest approach:

>> for st in s:
>>  if line.startswith(st):  do something

That means that if you are reading the lines from a file you'd need a 
neted loop:

for line in someFile:
   for substring in s:
  if line.startswith(substring):
 # do something here

Alternatively a regular exression match as suggested by others is 
probably
faster.

Alan G. 

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


Re: [Tutor] Invoking bash from within a python program

2005-08-14 Thread joe_schmoe
Danny Yoo wrote:
> 
> On Sat, 13 Aug 2005, Vinay Reddy wrote:
> 
> 
>>>Anyway, how do I call bash to run a program - e.g. slocate - from
>>>within a python program. I believe that I have to import the OS first
>>>(or do I?) and I was thinking something like:
>>>
>>>...
>>>sh slocate file_name > python_defined_list
>>
>>You can directly run slocate (or any other program) using the
>>os.popen* command. Refer to:
>>http://docs.python.org/lib/os-newstreams.html.
>>And you do need to import the os module.
> 
> 
> 
> Hi Joe,
> 
> Also, if you have a recent version of Python (Python 2.4), the
> 'subprocess' module might be worth a look:
> 
> http://www.python.org/doc/lib/module-subprocess.html
> 
> 
> 
> 
>>>This is to populate a list which would then become the filename list
>>>for the remove file command to iterate through sequentially and
>>>delete, as in:
>>>
>>>for i in python_defined_list:
>>>   rm -fr i
> 
> 
> 
> 'shutil' and its rmtree() function may be helpful for you:
> 
> http://www.python.org/doc/lib/module-shutil.html
> 
> Good luck!
> 
> 
Thanks Danny & Vinay

If I was to use the subprocess management module (as per Danny's 
suggestion), it looks like I should be able to invoke it using the 
shell=True argument. If my reading of 
http://www.python.org/doc/lib/node230.html is correct, this would enable 
the output of the command to be run through the shell (bash, in my case) 
without having to worry about piping the output back to the shell 
manually. This would then pass the list back to bash for it to iterate 
through the list to delete the filenames.

The basic idea I was toying around with is to create a delete/uninstall 
program that would take the output of slocate and iterate through that 
deleting all of the files associated with the program I wanted to 
uninstall without having to do so manually. Using tar balled source code 
does not seem to allow for an easy and straight forward way of 
uninstalling once the source directory has been deleted. I am also going 
to explore how to do this using bash and some basic shell programming 
and then work out which would be the better approach.

Thanks for your help folks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re and more ... read on

2005-08-14 Thread Bob Gailer
At 06:17 PM 8/13/2005, Jesse Lands wrote:
>I am trying to create a simple GUI that will track a network connection 
>using ping.  It's a starter project for me so I am sure there are other 
>easier ways of doing it, but I am learning, so bare with me.

Are we taking our clothes off? Reminds me of the old Adventure (Colossal 
Cave) game where the player decides to kill the bear. The response was 
"What! your bare hands against his *bear* hands?"

>I figured out the first part
>
>import os
>ping = os.popen('ping -c 4 10.0.8.200')
>ping_result = ping.read()
>
>
>I assume I have to use Regular Expression to read the results, but I don't 
>quite understand it.  Can someone explain it or point me in a direction to 
>where it's explained better then what I could find with google.

I don't know what links you found, but here are a few:
http://www.amk.ca/python/howto/regex/
http://www.regular-expressions.info/quickstart.html - this looks like a 
nice easy start tutorial

I suggest you post the output from ping and tell us what part of that you 
want. Then we can help more.

I also suggest learning re as it is a most useful tool. Yesterday I used 
urllib2 to grab a web page with many links to pdf files on it. SInce my 
broswer insists on opening instead of downloading such files, I used re to 
extract the urls from the links, then read and wrote each file. Since I am 
delighted with this code I post it in full. Notice especially the re.findall().

import urllib2, re
x = 
urllib2.urlopen(r'http://www.cde.state.co.us/cdeassess/csap/as_filelayouts.htm')
p = x.readlines()
# get just the lines containing '.pdf' the "easy way"
pdfs = [l for l in p if '.pdf' in l]
# pdfs[0] = '  Grades 3-10 CSAP 
Mathematics \r\n'
linkText = '\n'.join(pdfs) # convert the list to a string for re

# here I use re to grab text between the 2 "s
pdfs2 = re.findall(r'"(.*)"', linkText)

# findall = repeatedly apply the re until end of string
# r = treat following string literal as "raw" so one does not need to escape \
# the pattern "(.*)"  " = find a "; ( = begin a group . = match any character ;
# * = repeat matching the .;
# ) = end the group; " = stop matching the . when you find a ";
# using () to group ensures that just the part of the string that matches 
.* will be kept
# result is a list of desired strings
# pdfs2[0] = '2005/Mathematics%203-10%20DST%20grt%202005.pdf'

# In retrospect I could also have used re.findall(r'http://www.cde.state.co.us/cdeassess/csap/' + pdf
   try: # report and skip bad urls
 pn = urllib2.urlopen(url)
   except:
 print "Bad url:", url
 continue
   p = pn.read()
   z = file(outfile, 'wb')
   z.write(p)
   z.close()

BTW if you answered YES to the "What!" question you got "Congratulations - 
you just killed a bear."

Bob Gailer
303 442 2625 home
720 938 2625 cell 

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


Re: [Tutor] re

2005-08-14 Thread Alan G
> import os
> ping = os.popen('ping -c 4 10.0.8.200')
> ping_result = ping.read()
> 
> 
> I assume I have to use Regular Expression to read the results, 

You shouldn't need to. If I call ping I get somethjing like:

$ ping www.google.com
PING www.l.google.com (66.102.7.147): 56 data bytes
64 bytes from 66.102.7.147: icmp_seq=0 ttl=229 time=220 ms
64 bytes from 66.102.7.147: icmp_seq=1 ttl=229 time=188 ms
64 bytes from 66.102.7.147: icmp_seq=2 ttl=229 time=188 ms


So to read that I would just use the string.split() method to
break it into fields and the IP address is the 4th field 
and the time 7th.

But it depends on what exactly you want to do with it.
If you do want a basic intro to regex you can try my tutorial
topic on them. It doesn't cover the deeper bits but gives 
the 30% I use 70% of the time...

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Regexp with multiple patterns in Python

2005-08-14 Thread Kristian Evensen








Hello,

 

I am working on a way to
parse a file and wondered if there is a way to check for multiple patterns. The
reason I wonder this is because it would make everything a lot easier regarding
calculations on what words to use and so on.

 

What I want to do is to check
for two patterns to make sure all occurrences of pattern1 and pattern2 come in
the same order as they do in the file I parse. It it
contains a number of computer-games I would like the output to look something
like this:

PC, Battlefield, Battlefield2

PS2, Battlefield 2: Modern
Combat.

 

The file is constructed
somewhat similar to this:

PC

    Battlefield,
Battfiled2

PS2

    Battlefield
2: Modern Combat

 

Using the following
_expression_ (and re.findall) I get somewhat closer:

pattern8 = re.compile(r'search.asp\?title=battlefield.*?><.*?>(PCCD|XBOX
360|XBOX|PLAYSTATION PSP|PLAYSTATION 2) - TITLE<|game.asp\?id=(\d+).*?><.*?><.*?>(.*?)<')

 

The output is:

[('PCCD',
'', ''), ('PLAYSTATION 2', '', ''), ('XBOX', '', ''), ('XBOX 360', '', ''),
('PLAYSTATION PSP', '', ''), ('', '4262', '
Battlefield 2: Modern Combat')]

 

I get the last game mentioned
in the file, but none of the others.

 

Anybody know
how to solve this?

 

Thanks in advance for any
help and have a great day!

 

-Kristian






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


Re: [Tutor] Sorting a list of lists aka nested lists

2005-08-14 Thread jfouhy
Quoting Alan G <[EMAIL PROTECTED]>:

> > Quant.append( [ db_ticker, stock_close, MTD, 0, QTD, 0, YTD, 0, 
> > 0, 0 ] )
> > After Quant is created, I want to sort it by MTD. If I use a simple 
> > Quant.sort(), I assume its going to sort by 'db_ticker' which is not 
> > what I want.
> you need to write your own comparison function.
> Basically it will take two of your lists and return -1,0 or 1.
> 
> Or you can use Python's own logic to help
> 
> def cmplists(lst1,lst2):
>  return cmp(lst1[2],lst2[2])
> 
> Now you can sort Quant by passing your function into sort...

Note that in Python2.4+, you can use key= instead:

def sortKey(lst):
 return lst[2]
Quant.sort(key=sortKey)

This is more effient than specifying a different comparison function, because
the key function is only called once for each element.

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


Re: [Tutor] Invoking bash from within a python program

2005-08-14 Thread Vinay Reddy
> The basic idea I was toying around with is to create a delete/uninstall
> program that would take the output of slocate and iterate through that
> deleting all of the files associated with the program I wanted to
> uninstall without having to do so manually. Using tar balled source code
> does not seem to allow for an easy and straight forward way of
> uninstalling once the source directory has been deleted. I am also going
> to explore how to do this using bash and some basic shell programming
> and then work out which would be the better approach.

Why not: slocate |xargs rm -rf

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


[Tutor] parsing through an output stream

2005-08-14 Thread Vinay Reddy
Hi,
I tried running mplayer from a python program using the popen2 command
and read the returned output stream in non-blocking mode. But, I did
not getting any of the status messages given out by mplayer (I did get
the initial dump by mplayer).

I am using the following to read the output:
try: # get the last line of output
   for status in self.mplayerOut:
  if not status: break
  print status
except StandardError:
  pass

MPlayer terminates a status line with a '\r'. Is that the problem? If
so, I want python to recognize \r as a line terminator. How do I do
this?

Any help will be appreciated.

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


[Tutor] UTf-8 to Entity

2005-08-14 Thread Diaz, Wendell








Hey guys,

 

Hope you can help me on this.

 

I want to make a python program which opens an XML (UTF-8
encoding) and do a search & replace. It will search the Unicode and replace
them with their equivalent entity name. The program will read a look-up table
(a tab delimited text file) which list the unicodes
that needs to be replace with enity
names.

 

Example of the look-up table:

 

&nobreakspace; [tab]
000A0

 

Thanks in advance,

 

Wendell

 

 






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


[Tutor] Is it possible to...

2005-08-14 Thread Nathan Pinno



Is it possible to create a def that not only deals cards, but also assigns 
a value to each rank, except that the Jacks, Queens, and Kings all are the same 
value as the 10s?
 
If this is possible, how should I go about doing this?
 
Sorry if I'm asking what for most people is a basic question, but this one 
has been bugging me.
 
Nathan
---Early to 
bed,Early to rise,Makes a man healthy, wealthy, and wise.--Benjamin 
Franklin---
BEGIN:VCARD
VERSION:2.1
N:Pinno;Nathan;Paul;Mr.
FN:Pinno, Nathan Paul
NICKNAME:Spam_swatter
ORG:Woffee;Executive
TITLE:Owner/operator
TEL;WORK;VOICE:7806085529
TEL;CELL;VOICE:7806085529
ADR;WORK:;President/CEO;Box 1783;Camrose;Alberta;T4V1X7;Canada
LABEL;WORK;ENCODING=QUOTED-PRINTABLE:President/CEO=0D=0ABox 1783=0D=0ACamrose, Alberta T4V1X7=0D=0ACanada
ADR;HOME:;;Box 1783;Camrose;Alberta;T4V1X7;Canada
LABEL;HOME;ENCODING=QUOTED-PRINTABLE:Box 1783=0D=0ACamrose, Alberta T4V1X7=0D=0ACanada
X-WAB-GENDER:2
URL;HOME:http://falcon3166.tripod.com
URL;WORK:http://zoffee.tripod.com
BDAY:19850221
EMAIL;PREF;INTERNET:[EMAIL PROTECTED]
EMAIL;INTERNET:[EMAIL PROTECTED]
EMAIL;INTERNET:[EMAIL PROTECTED]
EMAIL;INTERNET:[EMAIL PROTECTED]
REV:20050815T055422Z
END:VCARD
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How can I make this run right?

2005-08-14 Thread Nathan Pinno



The following code is supposed to take in a number, and print 
number!:
n = int(raw_input("Number: "))x = n-1while 1:    
t = n*x    while x > 
1:    x -= 1    
else:    breakprint t
Why isn't it working, and how can I make it print out the correct 
output?
 
Thanks in advance,
Nathan
---Early to 
bed,Early to rise,Makes a man healthy, wealthy, and wise.--Benjamin 
Franklin---
BEGIN:VCARD
VERSION:2.1
N:Pinno;Nathan;Paul;Mr.
FN:Pinno, Nathan Paul
NICKNAME:Spam_swatter
ORG:Woffee;Executive
TITLE:Owner/operator
TEL;WORK;VOICE:7806085529
TEL;CELL;VOICE:7806085529
ADR;WORK:;President/CEO;Box 1783;Camrose;Alberta;T4V1X7;Canada
LABEL;WORK;ENCODING=QUOTED-PRINTABLE:President/CEO=0D=0ABox 1783=0D=0ACamrose, Alberta T4V1X7=0D=0ACanada
ADR;HOME:;;Box 1783;Camrose;Alberta;T4V1X7;Canada
LABEL;HOME;ENCODING=QUOTED-PRINTABLE:Box 1783=0D=0ACamrose, Alberta T4V1X7=0D=0ACanada
X-WAB-GENDER:2
URL;HOME:http://falcon3166.tripod.com
URL;WORK:http://zoffee.tripod.com
BDAY:19850221
EMAIL;PREF;INTERNET:[EMAIL PROTECTED]
EMAIL;INTERNET:[EMAIL PROTECTED]
EMAIL;INTERNET:[EMAIL PROTECTED]
EMAIL;INTERNET:[EMAIL PROTECTED]
REV:20050815T062214Z
END:VCARD
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor