Thursday, April 8, 2010

comp.lang.python - 26 new messages in 10 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* Generating a rainbow? - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/065e0b50c4aaca64?hl=en
* Py3: Read file with Unicode characters - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6cbf4d7d1d05c387?hl=en
* Why these don't work?? - 8 messages, 7 authors
http://groups.google.com/group/comp.lang.python/t/c24027648ce87df4?hl=en
* Replacing Periods with Backspaces - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/f47a20630aa3bab6?hl=en
* pass object or use self.object? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6f51302327b58aac?hl=en
* How to open and read an unknown extension file - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/570025039368c07b?hl=en
* ftp and python - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6183a96d88f4420b?hl=en
* regex help: splitting string gets weird groups - 6 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/9505c1de1fb8d879?hl=en
* Dynamically growing an array to implement a stack - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/a98cf3a9303bedbf?hl=en
* Recommend Commercial graphing library - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/b8609090d6ba19e9?hl=en

==============================================================================
TOPIC: Generating a rainbow?
http://groups.google.com/group/comp.lang.python/t/065e0b50c4aaca64?hl=en
==============================================================================

== 1 of 3 ==
Date: Thurs, Apr 8 2010 10:23 am
From: Chris Colbert


On Thu, Apr 8, 2010 at 1:14 PM, Tobiah <toby@rcsreg.com> wrote:
>> Look at the colorsys module.
>>
>> http://docs.python.org/library/colorsys.html?highlight=colorsys#module-
> colorsys
>
> That so rocks.  Thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>

How does that answer your original question?


== 2 of 3 ==
Date: Thurs, Apr 8 2010 10:14 am
From: Gary Herron


Tobiah wrote:
> I'm having a difficult time with this. I want
> to display a continuous range of hues using HTML
> hex representation (#RRGGBB). How would I go
> about scanning through the hues in order to
> make a rainbow?
>
> Thanks,
>
> Toby
>

Use the hue-saturation-value color space, and call hsv_to_rgb from the
standard Python library to convert to RGB. Enjoy!

Gary Herron


from colorsys import hsv_to_rgb

for hue ....:
rgb = hsv_to_rgb(hue, saturation, value)


Let 'hue' run from 0 (red) through 2/3 (blue) Hues from 2/3 to 1 get
into purples and magentas, which are not spectral (i.e., rainbow) colors.

Set 'saturation' to perhaps 0.5 (for a washed out effect) through 1.0
(for pure color). Even an intensely colorful rainbow has lots of white
light mixed in with it; a saturation of 0.5 is probably good.

Set 'value' to something in the range of 0 to 1 to control brightness.


== 3 of 3 ==
Date: Thurs, Apr 8 2010 11:34 am
From: Tobiah


> How does that answer your original question?

I was able to do this:

import colorsys

sat = 1
value = 1
length = 1000
for x in range(0, length + 1):
hue = x / float(length)
color = list(colorsys.hsv_to_rgb(hue, sat, value))
for x in range(3):
color[x] = int(color[x] * 255)
hexval = ("#%02x%02x%02x" % tuple(color)).upper()
print "<div style='height: 1; width: 500; background-color: %s'>"
% hexval


http://tobiah.org/rainbow.html

==============================================================================
TOPIC: Py3: Read file with Unicode characters
http://groups.google.com/group/comp.lang.python/t/6cbf4d7d1d05c387?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 8 2010 10:37 am
From: Gnarlodious


On Apr 8, 11:04 am, "Martin v. Loewis" wrote:

> That's because you need to re-learn some things.

Apparently so, every little item is a lesson. Thank you.

-- Gnarlie


==============================================================================
TOPIC: Why these don't work??
http://groups.google.com/group/comp.lang.python/t/c24027648ce87df4?hl=en
==============================================================================

== 1 of 8 ==
Date: Thurs, Apr 8 2010 11:10 am
From: "M. Hamed"


I'm trying the following statements that I found here and there on
Google, but none of them works on my Python 2.5, are they too old? or
newer?

"abc".reverse()
import numpy


== 2 of 8 ==
Date: Thurs, Apr 8 2010 11:31 am
From: nn


M. Hamed wrote:
> I'm trying the following statements that I found here and there on
> Google, but none of them works on my Python 2.5, are they too old? or
> newer?
>
> "abc".reverse()
> import numpy

reverse does not work on strings but does work on lists:
>>> x=list("abc")
>>> x.reverse()
>>> x
['c', 'b', 'a']

or maybe this:
>>> ''.join(reversed("abc"))
'cba'

as far as numpy you need to install it first:

http://pypi.python.org/pypi/numpy/


== 3 of 8 ==
Date: Thurs, Apr 8 2010 11:31 am
From: Mark Dickinson


On Apr 8, 7:10 pm, "M. Hamed" <mohammed.elshou...@microchip.com>
wrote:
> I'm trying the following statements that I found here and there on
> Google, but none of them works on my Python 2.5, are they too old? or
> newer?
>
> "abc".reverse()

This isn't valid Python in any version that I'm aware of. Where did
you see it? It wouldn't make a lot of sense anyway, since by analogy
with list.reverse you'd expect it to reverse the given string in
place. But that's not possible in Python, because strings are
immutable.

Maybe you're looking for something like:

>>> reversed("abc")
<reversed object at 0x100582810>

which works in versions of Python >= 2.4.

> import numpy

For this to work, you need to have numpy installed. numpy is a third-
party package that isn't part of the standard Python distribution;
for more information, see:

http://numpy.scipy.org/

The best method for installing numpy would depend on your system, and
on where you got Python from. On OS X, the system Python comes with
numpy as standard, for example. On Linux, there's probably a python26-
numpy package (or something with a similar name) that you can
install. On Windows: no idea. :)

Mark


== 4 of 8 ==
Date: Thurs, Apr 8 2010 11:43 am
From: MRAB


M. Hamed wrote:
> I'm trying the following statements that I found here and there on
> Google, but none of them works on my Python 2.5, are they too old? or
> newer?
>
> "abc".reverse()

Lists have a .reverse() method which reverses the list elements
in-place, but strings don't because they're immutable.

There's a built-in function reversed() which returns an iterator over an
iterable object, eg a string:

print reversed("abc")

for c in reversed("abc"):
print c

It's all in the documentation.

> import numpy

numpy isn't part of the standard library; you'd need to download and
install it.

== 5 of 8 ==
Date: Thurs, Apr 8 2010 1:08 pm
From: "M. Hamed"


Thanks All. That clears alot of confusion. It seems I assumed that
everything that works for lists works for strings (the immutable vs
mutable hasn't sunken in yet).

On the other hand (other than installing NumPy) is there a built-in
way to do an array full of zeros or one just like the numpy.zeros()? I
know I can do it with list comprehension (like [0 for i in
range(0,20)] but these are too many keystrokes for python :) I was
wondering if there is a simpler way.

I had another question about arrays but I should probably start
another thread.

Regards,

On Apr 8, 11:43 am, MRAB <pyt...@mrabarnett.plus.com> wrote:
> M. Hamed wrote:
> > I'm trying the following statements that I found here and there on
> > Google, but none of them works on my Python 2.5, are they too old? or
> > newer?
>
> > "abc".reverse()
>
> Lists have a .reverse() method which reverses the list elements
> in-place, but strings don't because they're immutable.
>
> There's a built-in function reversed() which returns an iterator over an
> iterable object, eg a string:
>
>      print reversed("abc")
>
>      for c in reversed("abc"):
>          print c
>
> It's all in the documentation.
>
> > import numpy
>
> numpy isn't part of the standard library; you'd need to download and
> install it.

== 6 of 8 ==
Date: Thurs, Apr 8 2010 1:27 pm
From: Emile van Sebille


On 4/8/2010 1:08 PM M. Hamed said...
> On the other hand (other than installing NumPy) is there a built-in
> way to do an array full of zeros or one just like the numpy.zeros()? I
> know I can do it with list comprehension (like [0 for i in
> range(0,20)] but these are too many keystrokes for python :) I was
> wondering if there is a simpler way.

map(lambda _:0, range(20))

Emile

== 7 of 8 ==
Date: Thurs, Apr 8 2010 1:36 pm
From: Robert Kern


On 2010-04-08 15:08 PM, M. Hamed wrote:

> On the other hand (other than installing NumPy) is there a built-in
> way to do an array full of zeros or one just like the numpy.zeros()? I
> know I can do it with list comprehension (like [0 for i in
> range(0,20)] but these are too many keystrokes for python :) I was
> wondering if there is a simpler way.

[0] * n

Of course, you should keep in mind that you shouldn't always be looking for
concise "built-in" expressions to do things. Or rather, you shouldn't be
disappointed if you don't find them. Almost always, the best solution is to wrap
up the ugly code into a function that you can then call everywhere. So even if
you were stuck with the list comprehension, you should have just defined your
own zeros() function that did the job and use it everywhere.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

== 8 of 8 ==
Date: Thurs, Apr 8 2010 1:37 pm
From: Joaquin Abian


On Apr 8, 10:08 pm, "M. Hamed" <mohammed.elshou...@microchip.com>
wrote:
> Thanks All. That clears alot of confusion. It seems I assumed that
> everything that works for lists works for strings (the immutable vs
> mutable hasn't sunken in yet).
>
> On the other hand (other than installing NumPy) is there a built-in
> way to do an array full of zeros or one just like the numpy.zeros()? I
> know I can do it with list comprehension (like [0 for i in
> range(0,20)] but these are too many keystrokes for python :) I was
> wondering if there is a simpler way.
>
> I had another question about arrays but I should probably start
> another thread.
>
> Regards,
>
> On Apr 8, 11:43 am, MRAB <pyt...@mrabarnett.plus.com> wrote:
>
> > M. Hamed wrote:
> > > I'm trying the following statements that I found here and there on
> > > Google, but none of them works on my Python 2.5, are they too old? or
> > > newer?
>
> > > "abc".reverse()
>
> > Lists have a .reverse() method which reverses the list elements
> > in-place, but strings don't because they're immutable.
>
> > There's a built-in function reversed() which returns an iterator over an
> > iterable object, eg a string:
>
> >      print reversed("abc")
>
> >      for c in reversed("abc"):
> >          print c
>
> > It's all in the documentation.
>
> > > import numpy
>
> > numpy isn't part of the standard library; you'd need to download and
> > install it.
>
>

if you want an array you can get it from module array

>> import array
>> array.array('i', [0]*100)
array('i', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

if you want simply a list:
>> [0] * 100
yields a list of hundred zeros

cheers
joaquin

==============================================================================
TOPIC: Replacing Periods with Backspaces
http://groups.google.com/group/comp.lang.python/t/f47a20630aa3bab6?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 8 2010 11:12 am
From: "Gabriel Genellina"


En Thu, 08 Apr 2010 12:26:56 -0300, Booter <colo.avs96@gmail.com> escribió:

> I am trying to replace a series of periods in a sting with backspaces
> that way I can easily parse information from a Windows command. the
> current statement I have for this is
>
> ***************************Statement************************************
> capture = re.sub('\.*', '\b', capture)

The * means "ZERO or more" occurrences - matching practically everywhere.
I think you want \.+ -- one or more occurrences of a literal period. To
actually have a \ in the string, you have to write it as "\\.+" or r"\.+"

> ===Out Put===
> str: \bi\bp\bc\bo\bn\bf\bi\bg\b \b/\ba\bl\bl\b\n\b\n\bW\bi\bn\bd\bo\bw
> \bs\b \bI\bP\b \bC\bo\bn\bf\bi\bg\bu\br\ba\bt\bi\bo\bn\b\n\b\n\b \b \b
> ==============================END============================
>
> which paces a bunch of '\b' strings throughout the string (to me at
> random). It sort of works if I use this command but I don't want
> there to be whitespace...

You want those \b, don't you? Just not everywhere...

> ===Out Put===
> str: ipconfig /all\n\nWindows IP Configuration\n\n Host
> Name : Triton\n Primary Dns Suffix :
> engrColoStateEDU\n Node Type : Hybrid\n IP Routing
> Enabled : No\n WINS Proxy Enabled : No\n DNS Suffix
> Search List : engrColoStateEDU
> \n ColoStateEDU\n\nEthernet
> adapter Local Area Connection:\n\n Connection-specific DNS
> Suffix : \n Description : Realtek PCIe GBE Family
> Controller\n Physical Address : 00-24-1D-16-FF-28\n DHCP
> Enabled : No\n Autoconfiguration Enabled : Yes\n
> IPv4 Address : 12982227254(Preferred) \n Subnet
> Mask : 2552552480\n Default Gateway :
> 129822241\n DNS Servers :
> 1298210378\n 1298210379\n
> NetBIOS over Tcpip : Enabled\n\nTunnel adapter
> isatap{04FB4DF5-4B41-4058-A641-6965D13CCC06}:\n\n Media
> State : Media disconnected\n Connection-specific DNS
> Suffix ...
> ==============END================================

Except for the last '...' I don't see any '.' in that string to be
replaced...

--
Gabriel Genellina


==============================================================================
TOPIC: pass object or use self.object?
http://groups.google.com/group/comp.lang.python/t/6f51302327b58aac?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 8 2010 11:25 am
From: Tim Arnold


On Apr 8, 4:20 am, Bruno Desthuilliers <bruno.
42.desthuilli...@websiteburo.invalid> wrote:
> Lie Ryan a écrit :
>
>
>
>
>
> > On 04/07/10 18:34, Bruno Desthuilliers wrote:
> >> Lie Ryan a écrit :
> >> (snip)
>
> >>> Since in function in python is a first-class object, you can instead do
> >>> something like:
>
> >>> def process(document):
> >>>     # note: document should encapsulate its own logic
> >>>     document.do_one_thing()
> >> Obvious case of encapsulation abuse here. Should a file object
> >> encapsulate all the csv parsing logic ? (and the html parsing, xml
> >> parsing, image manipulation etc...) ? Should a "model" object
> >> encapsulate the presentation logic ? I could go on for hours here...
>
> > Yes, but no; you're taking it out of context. Is {csv|html|xml|image}
> > parsing logic a document's logic? Is presentation a document's logic? If
> > they're not, then they do not belong in document.
>
> Is len() a list logic ? If yes, it should belong to list !-)
>
> There are two points here : the first is that we (that is, at least, you
> and me) just don't know enough about the OP's project to tell whether
> something should belong to the document or not. period. The second point
> is that objects don't live in a splendid isolation, and it's perfectly
> ok to have code outside an object's method working on the object.
>
> wrt/ these two points, your "document should encapsulate its own logic"
> note seems a bit dogmatic (and not necessarily right) to me - hence my
> answer.

The 'document' in this case is an lxml Elementtree, so I think it
makes sense to have code outside the object (e.g. static methods)
working on the object.
thanks,
--Tim

==============================================================================
TOPIC: How to open and read an unknown extension file
http://groups.google.com/group/comp.lang.python/t/570025039368c07b?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 8 2010 11:30 am
From: Kushal Kumaran


On Thu, Apr 8, 2010 at 10:39 PM, varnikat t <varnikat22@gmail.com> wrote:
> Hey,
> Thanks for the help.it detects now using glob.glob("*.*.txt")
> Can u suggest how to open and read file this way?
>
> if glob.glob("*.*.txt"):
>             file=open(glob.glob("*.*.txt"))
>             self.text_view.get_buffer().set_text(file.read())
>         else:
>             file=open(glob.glob("*.*.html"))
>             self.text_view.get_buffer().set_text(file.read())
>
> This gives error!!

glob.glob returns a list of filenames. You need to loop over it and
pass individual elements to the open function.

for item in glob.glob('*.txt'):
# item is a filename. pass it to open and process however you need

I don't know how the set_text method works, but it sounds like it
might not work right if you call it repeatedly with different
filenames.

--
regards,
kushal

==============================================================================
TOPIC: ftp and python
http://groups.google.com/group/comp.lang.python/t/6183a96d88f4420b?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 8 2010 12:08 pm
From: John Nagle


Anssi Saari wrote:
> John Nagle <nagle@animats.com> writes:
>
>> In theory, the FTP spec supports "three-way transfers", where the
>> source, destination, and control can all be on different machines.
>> But no modern implementation supports that.
>
> I remember even using that way back when, Unix machines in the 1990s.
>
> But, server to server transfers are supported even today, since it's
> part of the RFC. RFC959 explains how it's done in chapter 5.2. Usually
> this is called FXP now.
> http://en.wikipedia.org/wiki/Comparison_of_FTP_client_software lists a
> bunch of clients with FXP support. I don't know about doing this with
> ftplib, though.

Although the protocol allows setting up a 3-way transfer, many
FTP servers disallow data connections to an IP address different
from the control address. It's a security risk.

It's useful when you want to move data between machines with high
bandwidth connections, as within a server farm, and the control machine
has less bandwidth. But there are more modern approaches for that.

John Nagle

==============================================================================
TOPIC: regex help: splitting string gets weird groups
http://groups.google.com/group/comp.lang.python/t/9505c1de1fb8d879?hl=en
==============================================================================

== 1 of 6 ==
Date: Thurs, Apr 8 2010 11:49 am
From: gry


[ python3.1.1, re.__version__='2.2.1' ]
I'm trying to use re to split a string into (any number of) pieces of
these kinds:
1) contiguous runs of letters
2) contiguous runs of digits
3) single other characters

e.g. 555tHe-rain.in#=1234 should give: [555, 'tHe', '-', 'rain',
'.', 'in', '#', '=', 1234]
I tried:
>>> re.match('^(([A-Za-z]+)|([0-9]+)|([-.#=]))+$', '555tHe-rain.in#=1234').groups()
('1234', 'in', '1234', '=')

Why is 1234 repeated in two groups? and why doesn't "tHe" appear as a
group? Is my regexp illegal somehow and confusing the engine?

I *would* like to understand what's wrong with this regex, though if
someone has a neat other way to do the above task, I'm also interested
in suggestions.


== 2 of 6 ==
Date: Thurs, Apr 8 2010 12:40 pm
From: MRAB


gry wrote:
> [ python3.1.1, re.__version__='2.2.1' ]
> I'm trying to use re to split a string into (any number of) pieces of
> these kinds:
> 1) contiguous runs of letters
> 2) contiguous runs of digits
> 3) single other characters
>
> e.g. 555tHe-rain.in#=1234 should give: [555, 'tHe', '-', 'rain',
> '.', 'in', '#', '=', 1234]
> I tried:
>>>> re.match('^(([A-Za-z]+)|([0-9]+)|([-.#=]))+$', '555tHe-rain.in#=1234').groups()
> ('1234', 'in', '1234', '=')
>
> Why is 1234 repeated in two groups? and why doesn't "tHe" appear as a
> group? Is my regexp illegal somehow and confusing the engine?
>
> I *would* like to understand what's wrong with this regex, though if
> someone has a neat other way to do the above task, I'm also interested
> in suggestions.

If the regex was illegal then it would raise an exception. It's doing
exactly what you're asking it to do!

First of all, there are 4 groups, with group 1 containing groups 2..4 as
alternatives, so group 1 will match whatever groups 2..4 match:

Group 1: (([A-Za-z]+)|([0-9]+)|([-.#=]))
Group 2: ([A-Za-z]+)
Group 3: ([0-9]+)
Group 4: ([-.#=])

It matches like this:

Group 1 and group 3 match '555'.
Group 1 and group 2 match 'tHe'.
Group 1 and group 4 match '-'.
Group 1 and group 2 match 'rain'.
Group 1 and group 4 match '.'.
Group 1 and group 2 match 'in'.
Group 1 and group 4 match '#'.
Group 1 and group 4 match '='.
Group 1 and group 3 match '1234'.

If a group matches then any earlier match of that group is discarded,
so:

Group 1 finishes with '1234'.
Group 2 finishes with 'in'.
Group 3 finishes with '1234'.
Group 4 finishes with '='.

A solution is:

>>> re.findall('[A-Za-z]+|[0-9]+|[-.#=]', '555tHe-rain.in#=1234')
['555', 'tHe', '-', 'rain', '.', 'in', '#', '=', '1234']

Note: re.findall() returns a list of matches, so if the regex doesn't
contain any groups then it returns the matched substrings. Compare:

>>> re.findall("a(.)", "ax ay")
['x', 'y']
>>> re.findall("a.", "ax ay")
['ax', 'ay']


== 3 of 6 ==
Date: Thurs, Apr 8 2010 12:44 pm
From: Jon Clements


On 8 Apr, 19:49, gry <georgeryo...@gmail.com> wrote:
> [ python3.1.1, re.__version__='2.2.1' ]
> I'm trying to use re to split a string into (any number of) pieces of
> these kinds:
> 1) contiguous runs of letters
> 2) contiguous runs of digits
> 3) single other characters
>
> e.g.   555tHe-rain.in#=1234   should give:   [555, 'tHe', '-', 'rain',
> '.', 'in', '#', '=', 1234]
> I tried:>>> re.match('^(([A-Za-z]+)|([0-9]+)|([-.#=]))+$', '555tHe-rain.in#=1234').groups()
>
> ('1234', 'in', '1234', '=')
>
> Why is 1234 repeated in two groups?  and why doesn't "tHe" appear as a
> group?  Is my regexp illegal somehow and confusing the engine?
>
> I *would* like to understand what's wrong with this regex, though if
> someone has a neat other way to do the above task, I'm also interested
> in suggestions.

I would avoid .match and use .findall
(if you walk through them both together, it'll make sense what's
happening
with your match string).

>>> s = """555tHe-rain.in#=1234"""
>>> re.findall('[A-Za-z]+|[0-9]+|[-.#=]', s)
['555', 'tHe', '-', 'rain', '.', 'in', '#', '=', '1234']

hth,

Jon.


== 4 of 6 ==
Date: Thurs, Apr 8 2010 12:46 pm
From: Patrick Maupin


On Apr 8, 1:49 pm, gry <georgeryo...@gmail.com> wrote:
> [ python3.1.1, re.__version__='2.2.1' ]
> I'm trying to use re to split a string into (any number of) pieces of
> these kinds:
> 1) contiguous runs of letters
> 2) contiguous runs of digits
> 3) single other characters
>
> e.g.   555tHe-rain.in#=1234   should give:   [555, 'tHe', '-', 'rain',
> '.', 'in', '#', '=', 1234]
> I tried:>>> re.match('^(([A-Za-z]+)|([0-9]+)|([-.#=]))+$', '555tHe-rain.in#=1234').groups()
>
> ('1234', 'in', '1234', '=')
>
> Why is 1234 repeated in two groups?  and why doesn't "tHe" appear as a
> group?  Is my regexp illegal somehow and confusing the engine?
>
> I *would* like to understand what's wrong with this regex, though if
> someone has a neat other way to do the above task, I'm also interested
> in suggestions.

IMO, for most purposes, for people who don't want to become re
experts, the easiest, fastest, best, most predictable way to use re is
re.split. You can either call re.split directly, or, if you are going
to be splitting on the same pattern over and over, compile the pattern
and grab its split method. Use a *single* capture group in the
pattern, that covers the *whole* pattern. In the case of your example
data:

>>> import re
>>> splitter=re.compile('([A-Za-z]+|[0-9]+|[-.#=])').split
>>> s='555tHe-rain.in#=1234'
>>> [x for x in splitter(s) if x]
['555', 'tHe', '-', 'rain', '.', 'in', '#', '=', '1234']

The reason for the list comprehension is that re.split will always
return a non-matching string between matches. Sometimes this is
useful even when it is a null string (see recent discussion in the
group about splitting digits out of a string), but if you don't care
to see null (empty) strings, this comprehension will remove them.

The reason for a single capture group that covers the whole pattern is
that it is much easier to reason about the output. The split will
give you all your data, in order, e.g.

>>> ''.join(splitter(s)) == s
True

HTH,
Pat


== 5 of 6 ==
Date: Thurs, Apr 8 2010 1:02 pm
From: Tim Chase


gry wrote:
> [ python3.1.1, re.__version__='2.2.1' ]
> I'm trying to use re to split a string into (any number of) pieces of
> these kinds:
> 1) contiguous runs of letters
> 2) contiguous runs of digits
> 3) single other characters
>
> e.g. 555tHe-rain.in#=1234 should give: [555, 'tHe', '-', 'rain',
> '.', 'in', '#', '=', 1234]
> I tried:
>>>> re.match('^(([A-Za-z]+)|([0-9]+)|([-.#=]))+$', '555tHe-rain.in#=1234').groups()
> ('1234', 'in', '1234', '=')
>
> Why is 1234 repeated in two groups? and why doesn't "tHe" appear as a
> group? Is my regexp illegal somehow and confusing the engine?

well, I'm not sure what it thinks its finding but nested capture-groups
always produce somewhat weird results for me (I suspect that's what's
triggering the duplication). Additionally, you're only searching for
one match (.match() returns a single match-object or None; not all
possible matches within the repeated super-group).

> I *would* like to understand what's wrong with this regex, though if
> someone has a neat other way to do the above task, I'm also interested
> in suggestions.

Tweaking your original, I used

>>> s='555tHe-rain.in#=1234'
>>> import re
>>> r=re.compile(r'([a-zA-Z]+|\d+|.)')
>>> r.findall(s)
['555', 'tHe', '-', 'rain', '.', 'in', '#', '=', '1234']

The only difference between my results and your results is that the 555
and 1234 come back as strings, not ints.

-tkc


== 6 of 6 ==
Date: Thurs, Apr 8 2010 1:36 pm
From: gry


On Apr 8, 3:40 pm, MRAB <pyt...@mrabarnett.plus.com> wrote:

...
> Group 1 and group 4 match '='.
> Group 1 and group 3 match '1234'.
>
> If a group matches then any earlier match of that group is discarded,
Wow, that makes this much clearer! I wonder if this behaviour
shouldn't be mentioned in some form in the python docs?
Thanks much!

> so:
>
> Group 1 finishes with '1234'.
> Group 2 finishes with 'in'.
> Group 3 finishes with '1234'.


==============================================================================
TOPIC: Dynamically growing an array to implement a stack
http://groups.google.com/group/comp.lang.python/t/a98cf3a9303bedbf?hl=en
==============================================================================

== 1 of 3 ==
Date: Thurs, Apr 8 2010 1:21 pm
From: "M. Hamed"


I have trouble with some Python concept. The fact that you can not
assign to a non-existent index in an array. For example:

a = [0,1]
a[2] =========> Generates an error

I can use a.append(2) but that always appends to the end. Sometimes I
want to use this array as a stack and hence my indexing logic would be
something like:

If you are already at the end (based on your stack pointer):
use append() then index (and inc your pointer)
if not:
index directly (and inc your stack pointer)

If feel that doing this everytime I want to add an element that I have
to check whether it exists or not is too much. Is there any simpler
way to do this?

I know I can do something like this:

a = numpy.zeros(MAX_STACK_SIZE)

but I don't want to predetermine the stack size.

Any help?

Thanks


== 2 of 3 ==
Date: Thurs, Apr 8 2010 1:29 pm
From: Paul McGuire


On Apr 8, 3:21 pm, "M. Hamed" <mhels...@hotmail.com> wrote:
> I have trouble with some Python concept. The fact that you can not
> assign to a non-existent index in an array. For example:
>
> a = [0,1]
> a[2] =========> Generates an error
>
> I can use a.append(2) but that always appends to the end. Sometimes I
> want to use this array as a stack and hence my indexing logic would be
> something like:
>
> If you are already at the end (based on your stack pointer):
>       use append() then index (and inc your pointer)
> if not:
>       index directly (and inc your stack pointer)

??? The stack pointer is *always* at the end, except don't actually
keep a real stack pointer, let list do it for you. Call append to
push a value onto the end, and pop to pull it off. Or if you are
really stuck on push/pop commands for a stack, do this:

>>> class stack(list):
... push = list.append
...
>>> ss = stack()
>>> ss.push("x")
>>> ss.push("Y")
>>> ss
['x', 'Y']
>>> ss.pop()
'Y'
>>> ss.pop()
'x'
>>> ss.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list

-- Paul


== 3 of 3 ==
Date: Thurs, Apr 8 2010 1:29 pm
From: Patrick Maupin


On Apr 8, 3:21 pm, "M. Hamed" <mhels...@hotmail.com> wrote:
> I have trouble with some Python concept. The fact that you can not
> assign to a non-existent index in an array. For example:
>
> a = [0,1]
> a[2] =========> Generates an error
>
> I can use a.append(2) but that always appends to the end. Sometimes I
> want to use this array as a stack and hence my indexing logic would be
> something like:
>
> If you are already at the end (based on your stack pointer):
>       use append() then index (and inc your pointer)
> if not:
>       index directly (and inc your stack pointer)
>
> If feel that doing this everytime I want to add an element that I have
> to check whether it exists or not is too much. Is there any simpler
> way to do this?
>
> I know I can do something like this:
>
> a = numpy.zeros(MAX_STACK_SIZE)
>
> but I don't want to predetermine the stack size.
>
> Any help?
>
> Thanks

Well, if you never want to add intermediate data between your new
element and the stack, you can just do:

stack[index:index + 1] = [newelement]

Regards,
Pat

==============================================================================
TOPIC: Recommend Commercial graphing library
http://groups.google.com/group/comp.lang.python/t/b8609090d6ba19e9?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 8 2010 1:33 pm
From: Giacomo Boffi


Grant Edwards <invalid@invalid.invalid> writes:

> If it's 2D data, you don't need to use a 3D graph.

if it's tabular data, you don't need an uber-histogram
--
giampippetto, coso, come si chiama? ah si` "MMAX" ha scritto:
> Tra il trascendente e l'interpretazione prevalente del dato come
> assioma ne passa...


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate