pyparser and recursion problem


On 2007-07-26, pyscottishguy@hotmail.com wrote:
> Using pyparser, I'm trying to parse a string like this:
>
>:Start: first SECOND THIRD :SECOND: second1 | second2 :THIRD: third1 |
> FOURTH :FOURTH: fourth1 | fourth2
>
> I want the parser to do the following:
> 1) Get the text for the :Start: label e.g ('first SECOND THIRD')
> 2) Do nothing with the lower-case words e.g ('first')
> 3) For each upper-case word find the corresponding entries, and
> replace the word
> with these entries (the '|' indicates separate records)
> e.g. for 'SECOND', replace the word with ("second1", "second2")
> 4 Do this recursively, because each item in '3' can have upper-case
> words
>
> I can do this - but not within pyparser. I had to write a
> recursive function to do it. I would like to do it within
> pyparser however.

pyparser is a great parser, but out of the box it only parses. To
get it to convert a text file into a new form you'll have to
write most of the conversion code yourself, and merely hook it
into pyparser.

The critical step you're missing (and that I missed until my
third try) is the setParseAction method, with which you can
monkey around with the resulting parse tree.

On the other hand, since you got it working without pyparsing,
probably you're problem doesn't need pyparsing.

Hopefully I'll have time to help you a bit more later, or Paul
MaGuire will swoop down in his pyparsing powered super-suit.

--
Neil Cerutti
, ,

Posted On: Monday 5th of November 2012 02:22:40 AM Total Views:  243
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




Re: Why is recursion so slow?

On Sun, 29 Jun 2008 10:03:46 -0400, Dan Upton wrote: >On Sun, Jun 29, 2008 at 1:27 AM, Terry Reedy wrote: >> >> >> slix wrote: >>> >>> Recursion is awesome for writing some functions, like searching trees >>> etc but wow how can it be THAT much slower for computing fibonacci- >>> numbers >> >> The comparison below has nothing to do with recursion versus iteration. (It >> is a common myth.) You (as have others) are comparing an exponential, >> O(1.6**n), algorithm with a linear, O(n), algorithm. >> > >FWIW, though, it's entirely possible for a recursive algorithm with >the same asymptotic runtime to be wall-clock slower, just because of >all the extra work involved in setting up and tearing down stack >frames and executing call/return instructions. (If the function is >tail-recursive you can get around this, though I don't know exactly >how CPython is implemented and whether it optimizes that case.) CPython doesn't do tail call elimination. And indeed, function calls in Python have a much higher fixed overhead than iteration. Jean-Paul
VIEWS ON THIS POST

105

Posted on:

Saturday 3rd November 2012
View Replies!

Re: bad recursion, still works

On Jul 16, 1:09pm, Jeff wrote: > On Jul 15, 7:21pm, Michael Torrie wrote: > > > iu2 wrote: > > > I still don't understand: In each recursive call to flatten, acc > > > should be bound to a new [], shouldn't it Why does the binding happen > > > only on the first call to flatten > > > Nope. In each new call it's (re)bound to the same original list, which > > you've added to as your function continues--it's mutable. Default > > variables that are bound to mutable objects are one of the big caveats > > that is mentioned in the FAQ. > > Is this avoidable by using a call to list() in the definition instead No. Probably what you'd want to do, is something like this: def func(arg1, arg2=None): if arg2 is None: arg2 = list() ... So you create a list at runtime if arg2 has its default value.
VIEWS ON THIS POST

297

Posted on:

Sunday 4th November 2012
View Replies!

maximum recursion depth?

i received an error maximum recursion depth when processing large amounts of data. i dont know exactly how many recursive calls i made but id assume 50000 or so. is there a definitie limit to the nbr of calls or is the memory that runs out is that then the RAMmemory is there a special amount of memory assigned for python or it just takes and takes until windows runs out of it
VIEWS ON THIS POST

165

Posted on:

Sunday 4th November 2012
View Replies!

bad recursion, still works

I wrote this wrong recursive function that flattens a list: def flatten(lst, acc=[]): #print 'acc =', acc, 'lst =', lst if type(lst) != list: acc.append(lst) else: for item in lst: flatten(item) return acc a = [1, 2, [3, 4, 5], [6, [7, 8, [9, 10], 11], 12], 13, 14] b = flatten(a) print b I was amazed to realize that it flattens the list alright. Why 'acc' should be an empty list on each invocation of flatten, but is seems to accumulate anyway...
VIEWS ON THIS POST

107

Posted on:

Sunday 4th November 2012
View Replies!

Why is recursion so slow?

Recursion is awesome for writing some functions, like searching trees etc but wow how can it be THAT much slower for computing fibonacci- numbers is the recursive definition counting fib 1 to fib x-1 for every x is that what lazy evaluation in functional languages avoids thus making recursive versions much faster is recursive fibonacci in haskell as fast as an imperative solution in a procedural language def fibr(nbr): if nbr > 1: return fibr(nbr-1) + fibr(nbr-2) if nbr == 1: return 1 if nbr == 0: return 0 def fibf(n): sum=0 a=1 b=1 if n slix wrote: > Recursion is awesome for writing some functions, like searching trees > etc but wow how can it be THAT much slower for computing fibonacci- > numbers The comparison below has nothing to do with recursion versus iteration. (It is a common myth.) You (as have others) are comparing an exponential, O(1.6**n), algorithm with a linear, O(n), algorithm. > def fibr(nbr): > if nbr > 1: > return fibr(nbr-1) + fibr(nbr-2) > if nbr == 1: > return 1 > if nbr == 0: > return 0 This is exponential due to calculating fib(n-2) twice, fib(n-3) thrice, fib(n-4) 5 times, fir(n-5) 8 times, etc. (If you notice an interesting pattern, you are probably correct!) (It returns None for n < 0.) If rewritten as iteratively, with a stack, it is still exponential. > def fibf(n): > sum=0 > a=1 > b=1 > if n for i in range(3,n+1): > sum=a+b > a=b > b=sum > return sum This is a different, linear algorithm. fib(i), 0
VIEWS ON THIS POST

106

Posted on:

Sunday 4th November 2012
View Replies!

recursion

Can someone explain me this >>> def f(l): if l == []: return [] else: return f(l[1:]) + l[:1] #
VIEWS ON THIS POST

145

Posted on:

Monday 5th November 2012
View Replies!

insert string problems..

Hi.. I want to insert some data to postgresql.. My insert code: yer="019" cursor.execute("INSERT INTO ids_%s (id) VALUES (%s)", (yer, id)) I don't want to use % when the insert operation. in this code give me this error: psycopg2.ProgrammingError: syntax error at or near "'019'" LINE 1: SELECT link_id from linkkeywords_'019' if i do int(yer) , 019 change to 19 .. How can i do int yer string with 0
VIEWS ON THIS POST

182

Posted on:

Monday 5th November 2012
View Replies!

A problem with Time

, I need to return the date yesterday in the form DDMMYYYY. I looked through the modules: time, datetime and calendar but can't find anything that leaps out at me. The problem I'm having is that although I can use time.localtime and get a tuple of the year, month, day and so forth, I don't believe I can just minus 1 from the day, because I don't think it's cyclic, also, I can't see the date being linked in with the month. So is there any way of getting yesterdays date Thank You Dominic
VIEWS ON THIS POST

161

Posted on:

Monday 5th November 2012
View Replies!

Socket communication problem

Sandy Dunlop wrote: > > I'm new here, and fairly new to Python. I have been playing around with > Python and started having a look at socket IO. I have written a script > that communicates over a network to a server which is written in C. > While trying to get this working, I have been running into a problem > where the Python client appears to hang when it should be receiving data > back from the server. I forgot to add, I'm using Python 2.5.1 on OS X, and have also tried my program under Python 2.5.1 on Solaris 9. Cheers, Sandy
VIEWS ON THIS POST

146

Posted on:

Monday 5th November 2012
View Replies!

Using arrays in Python - problems.

, ! I've just started to use Python and its a lovely language! I've previously programmed in Fortran 95 and have just began to use numpy. I'm having a few problems with arrays in Python though and wondered if someone could offer me some advice I wrote the following Fortran code to randomly generate numbers from a log-normal distribution for use in a Monte Carlo model: do n=1,shotcount F(n)=G05DEF(F_mean,F_sd) enddo The array F(n) is dynamically allocated earlier on and is sized with reference to shotcount, the number of iterations the model performs. The problem is I can't get something like this to run in Python using numpy, and for the size of the array to be sized dynamically with reference to the variable shotcount. I acknowledge that my knowledge of Python is still really basic (I only started learning it a few days ago) and I'm trying to get out of the Fortran programming mindset but I'm stuck and don't seem to be able to get any further. If anyone could help I'd be really grateful.
VIEWS ON THIS POST

240

Posted on:

Monday 5th November 2012
View Replies!

problem with Python class creating

Hi all, I have the code like this one: from myMisc import ooIter class MyClass: def __init__(self): pass iterfcn = lambda *args: ooIter(self) # i.e pass the class instance to other func named ooIter field2 = val2 field3 = val3 # etc So it yields "global name 'self' is not defined", that is true. How could I handle the situation Currently I do (and it works, but give me some troubles - I should call MyClass.__init__ for each children class, and there are lots of those ones) class MyClass: def __init__(self): iterfcn = lambda *args: ooIter(self) # i.e pass the class instance to other func named ooIter field2 = val2 field3 = val3 # etc I suspect it has better solution, is it Thank you in advance, Dmitrey
VIEWS ON THIS POST

238

Posted on:

Monday 5th November 2012
View Replies!

regexp problem in Python

I want to find "http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.wmvtsid=20070803-164051-9d637d11" or 3gp instead of wmv in the text file like this : ""some code"" function reportAbuse() { var windowname="abuse"; var url="/abuse.jsplink=" + "http://www.2shared.com/file/1716611/ e2000f22/Jadeed_Mlak14.html"; OpenWindow = window.open(url,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500,height=500,left=50,top=50'); OpenWindow.focus(); } function startDownload(){ window.location = "http://www.2shared.com/download/1716611/ e2000f22/Jadeed_Mlak14.wmvtsid=20070803-164051-9d637d11"; //document.downloadForm.submit(); } http://www.2shared.com/download/1716611/e2000f22/ Jadeed_Mlak14.3gptsid=20070803-164051-9d637d11"sfgsfgsfgv I use this pattern : "http.*\.(wmv|3gp).*"" but it returns only 'wmv' and '3gp' instead of "http://www.2shared.com/ download/1716611/e2000f22/Jadeed_Mlak14.wmv tsid=20070803-164051-9d637d11" what can I do what's wrong whit this pattern thanx for your comments
VIEWS ON THIS POST

174

Posted on:

Monday 5th November 2012
View Replies!

problems playing with dates from any month.

hello, I have a very strange problem and I can't find any solution for that. I am working on an accounting package which I wish to develop in python. the simple problem is that I want to knoe how I can know if the given date is the nth day of a month. for example if a customer is supposed to pay his installment on every 5th of all months, I want to know if today is the fifth day (jan the fifth, feb the fifth etc) for any given month. I have not found any such function. if I have looked (or over looked ) in the wrong places I am really sorry. secondly I also want to know the way in which I can convert a given string to a date object. for example if I have a string "29/09/2005", I know it is a valid date although it is in a string form. now I want to convert the above string into a real date object. how can I cast it this way regards, Krishnakant.
VIEWS ON THIS POST

210

Posted on:

Monday 5th November 2012
View Replies!

Re: problems playing with dates from any month.

krishnakant Mane wrote: > On 02/08/07, Ian Clark wrote: > >> http://docs.python.org/lib/node85.html >> > I looked there even before. > but could not figure out what the code did. > I know in that variable called s there was a string in a valid date format. > but when datetime.strptime was used, I did not understand the place > where a date object say d was created. > I would expect some thing like d = and the function. but I did not fine that. > only reference was the datetime module and the documentation is not as good. >>> import datetime >>> import time >>> fmt_string = '29/05/2005' >>> date_tuple = time.strptime(fmt_string, '%d/%m/%Y') >>> print date_tuple (2005, 5, 29, 0, 0, 0, 6, 149, -1) >>> date_tuple_minus_tz = date_tuple[0:6] >>> print date_tuple_minus_tz (2005, 5, 29, 0, 0, 0) >>> date_obj = datetime.datetime(*date_tuple_minus_tz) This last line is equivalent to the following: >>> date_obj = datetime.datetime(2005, 5, 29, 0, 0, 0) The * in front of a tuple expands it's arguments when making a function call >>> print date_obj 2005-05-29 00:00:0 >>> print date_obj.day == 5 False > another question I am getting is that where is the list of all > formatting characters. like for example Y is 4 digit year M is month > MM is month in 2 digits etc. > I am trying to locate a list of all these denoters. > can you provide me the place http://docs.python.org/lib/module-time.html Look for the strptime() function. > > >> Then it's just: >> >> if date_obj.day == 5: >> print 'It's the fifth day of the month' >> > this was much better than the documentation,
VIEWS ON THIS POST

200

Posted on:

Monday 5th November 2012
View Replies!

Matplotlib axis control problem

I would like to control the y axis of a plot. The following code does exactly what I want it to! On my linux computer it sets the y axis limits to 18.0 minimum, 58.0 maximum, plots some points on y=x, provides ticks at 20,30,40,50 and horizontal tick lines that intersect the plotted points. very good, but if I change the upper y axis limit to 54.0, (ax.set_ylim(18.0, 54.0)), it fails, plotting the ticks at some strange values. Ultimately I want to uncomment the set scale to log and use this to label semi log plots that by default are only labeled on powers of 10. My data falls within one decade so I don't want the full 10-100 limits. I'm rather new at matplotlib so if I'm making trivial errors please feel free to criticize.
VIEWS ON THIS POST

157

Posted on:

Monday 5th November 2012
View Replies!

Re: problem with change to exceptions

En Fri, 27 Jul 2007 19:49:17 -0300, Neal Becker escribi: > import exceptions > > class nothing (exceptions.Exception): > def __init__ (self, args=None): > self.args = args > > if __name__ == "__main__": > raise nothing > > Traceback (most recent call last): > File "", line 1, in > File "/usr/tmp/python-3143hDH", line 5, in __init__ > self.args = args > TypeError: 'NoneType' object is not iterable > > I'll have to say, I don't understand this error. If this is all your code, try using just: class nothing(Exception): pass if __name__ == "__main__": raise nothing Exceptions are built-in since aeons ago, so you don't have to import the exceptions module. The standard Exception class has an "args" attribute, and it's expected to be a tuple (not None). See -- Gabriel Genellina
VIEWS ON THIS POST

254

Posted on:

Monday 5th November 2012
View Replies!

Strange problems with subprocess

Hi all. I have a simple "ping tester" program that, every 1 minute (execute by linux crontab), create, with subprocess, a "ping -c 1 my_addrs". work, but sometime (about 1/2 times at a day), I receive this error message: File "/exports/srv-wipex/net_test/ping_tester.py", line 88, in pyPing cmd_p = Popen(cmd, stdout=PIPE, stderr=PIPE) File "subprocess.py", line 543, in __init__ errread, errwrite) File "subprocess.py", line 970, in _execute_child data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB What can be that raise this Python 2.4 in deb etch
VIEWS ON THIS POST

352

Posted on:

Monday 5th November 2012
View Replies!

Re: problem with change to exceptions

Neal Becker wrote in news:f8e0g4$o1u$1@sea.gmane.org: > Alex Popescu wrote: > >> Neal Becker wrote in >> news:f8dspe$fm2$1@sea.gmane.org: >> > > [snip...] > >>> >> >> You can pass to the exception: >> a) a string (it will become the message) >> b) a tuple of values (can it be a list also) >> >> In your case there is no message, no values so args is NoneType. >> > Yes, args is None. So the assignment: > self.args = args > > should set self.args to None. Nothing wrong there, and what has this > got to do with NoneType being iterable > args are used to generate the traceback when a message was not provided. ../alex -- ..w( the_mindstorm )p.
VIEWS ON THIS POST

180

Posted on:

Monday 5th November 2012
View Replies!

Xinetd & python server script. problem to get data from from client

I wrote simple script to test communication: When i connect via telnet like: "telnet localhost 51423" the server is working send and receive information. but when i connected to him via client scrip so client script receive messages from server but server doesn't receive message from client. In xinetd.conf and servers conf file "only_from = 0.0.0.0/0" already choosen. What can i do Here below are my client and server: Thank you Server: #!/usr/bin/env python # example import sys import os print "Wellcome" print "please enter the string" sys.stdout.flush() line = sys.stdin.readline().strip() print "You entered %d characters." % len(line) sys.stdout.flush() client: import sys import string import os import time import socket import popen2 PORT = 51423 HOST = ""#sys.argv[1] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) print "Connected from:", sock.getsockname() print "Connected to:",sock.getpeername() while 1: print "waiting" result = sock.recv(1024) print result sock.send('foo') print "Sent: foo" if result == 3: break
VIEWS ON THIS POST

267

Posted on:

Monday 5th November 2012
View Replies!

"struct" module problem w/ pyinstaller

, I am trying to create exectuables on inux using "pyinstaller". I am using pyinstaller-1.3, RHEL 4.4, Python 2.5. The executables fail to run. The problem returned is pertaining to "struct.py" not being able to find the module "_struct". struct.py is located under /usr/local/lib/python-2.5/, and there is a _struct.o (no _struct.py anywhere) located under /usr/local/lib/ python-2.5/lib-dynload. When trying to run the executable, the loader returns: File "/usr/local/lib/python2.5/struct.py", line 30, in ImportError: No module named _struct The line in question is: from _struct import Struct, error I am a python neophyte. If someone could give me some information, I would appreciate it.
VIEWS ON THIS POST

149

Posted on:

Monday 5th November 2012
View Replies!