473,387 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

replacing all 'rng's in a buffer with consecutive r[1], r[2]'s

I read a file into a buffer and subject it to re.sub()
I can replace every occurrence of a pattern with a fixed string but when
I try to replace each occurrence with a string that changes (by having
an incrementing number in it, (ie 'repTxt[1]','repTxt[2]'etc), I note
that the incrementing number generator function, I'm calling in
re.sub(), (which works fine outside it), seems to be evaluated only once
and is therefore not incrementing the number.

Can someone please show me a working eg of how to replace 'rng' in a
file with 'r[1]', 'r[2]' etc. This is my first Python program so any
help would be very gratefully received.

Here's my code

Expand|Select|Wrap|Line Numbers
  1. #read orig file into buf & close file
  2. import re
  3. infile = file('pyInfile', 'r')
  4. buf = infile.read()
  5. infile.close()
  6. print buf
  7.  
  8. #replace all allocated streams with 'rng'
  9. print '=========== orig buf ============'; print buf
  10. pat = re.compile('r\[\d+\]')
  11. buf = pat.sub("rng", buf, 0)
  12.  
  13. #now replace all 'rng's with consecutive streams
  14. #===============================================
  15. def static_num():
  16. ''' this is a generator function that avoids globals
  17. yield differentiates fn as generator fn which freezes
  18. '''
  19. x = 0
  20. while True:
  21. x += 1
  22. yield str(x)
  23.  
  24. static = static_num().next
  25.  
  26. pat = re.compile('rng')
  27. #there is a problem in that static only seems to get called once.
  28. #need to invoke this every time you get a match for it to
  29. #increment
  30. buf = pat.subn('rng[' + static() + ']', buf, 0)
  31. print 'static() incrementing ok ' + static()
  32. print 'static() incrementing ok ' + static()
  33. print '=========== changed to ============'; print buf[0]
  34. #outfile = file('pyOutfile', 'w')
  35. #outfile.write(buf)
  36.  

Oct 4 '06 #1
2 1030
m g william wrote:
I read a file into a buffer and subject it to re.sub()
I can replace every occurrence of a pattern with a fixed string but when
I try to replace each occurrence with a string that changes (by having
an incrementing number in it, (ie 'repTxt[1]','repTxt[2]'etc), I note
that the incrementing number generator function, I'm calling in
re.sub(), (which works fine outside it), seems to be evaluated only once
and is therefore not incrementing the number.

Can someone please show me a working eg of how to replace 'rng' in a
file with 'r[1]', 'r[2]' etc. This is my first Python program so any
help would be very gratefully received.

buf = pat.subn('rng[' + static() + ']', buf, 0)
You'll have to repeat that to get the desired effect:

pat = re.compile("rng")
replacements = 1
while replacements:
buf, replacements = pat.subn("r[" + static() + "]", buf, 1)
print buf

but there is a more efficient alternative

def fsub(match):
return "r[" + static() + "]"
buf = re.sub("rng", fsub, buf)

that would still work if you were to replace 'rng' with 'rng[1]',
'rng[2]'...

Peter
Oct 4 '06 #2
"m g william" <mg*******@blueyonder.co.ukwrote in message
news:ma***************************************@pyt hon.org...
<snip>
#now replace all 'rng's with consecutive streams
#===============================================
def static_num():
''' this is a generator function that avoids globals
yield differentiates fn as generator fn which freezes
'''
x = 0
while True:
x += 1
yield str(x)

static = static_num().next
Also, check out itertools.count (one of many tools from the excellent
itertools module), as in:

static - itertools.count().next

- no need to roll this function for yourself. You still need to call it for
each substitution, though, as described elsewhere.

-- Paul
Oct 4 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Xah Lee | last post by:
i have a bunch of java files that has spaced-out formatting that i want to get rid of. I want to replace two end of line characters by one end of line characters. The files in question is unix, and...
13
by: yaipa | last post by:
What would be the common sense way of finding a binary pattern in a ..bin file, say some 200 bytes, and replacing it with an updated pattern of the same length at the same offset? Also, the...
4
by: Chad | last post by:
Hello, im struggleing,Im trying to replace a line in a file. 1|010000 1|010001 1|010002 0|010003 <-- replace this with 1|10003 0|010004 0|010005 .... all of the strings are the same length.
7
by: Skybuck Flying | last post by:
Hi, if (__builtin_expect (!buffer->__init, 0)) { buffer->__a = 0x5deece66dull; buffer->__c = 0xb; buffer->__init = 1; } I am using visual c 6 and this code doesn't compile, it's probably...
5
by: ilias | last post by:
Hi, I am running a C++ code in multiple environments/clusters. Until now I was using the standart rand() function as RNG. The problem is that I want to be able to stop my code and start it again...
32
by: FireHead | last post by:
Hello C World & Fanatics I am trying replace fgets and provide a equavivalant function of BufferedInputReader::readLine. I am calling this readLine function as get_Stream. In the line 4 where...
7
by: Christopher Pisz | last post by:
I found an article http://spec.winprog.org/streams/ as a starting point, but it seems to do alot of things that aren't very standard at all. One particular problem is, that he is using a vector as...
2
by: DotNetNewbie | last post by:
Hi, I want to replace all consecutive (2 or more) dashes into a single dash. So text like "hello--world is-cool------ok?" should become "hello-word is-cool-ok?" so it doesn't effect...
26
by: Adem24 | last post by:
I need a good and fast random number generator (RNG), and a linear congruential generator (LCG), both with a max period >= 31 bits; the bigger the better. Additional requirements: - Must use ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.