views:

131

answers:

2

Hello, I have html-file. I have to replace all text between this: [%anytext%]. As I understand, it's very easy to do with BeautifulSoup for parsing hmtl. But what is regular expression and how to remove&write back text data?


Okay, here is the sample file:

<html>
  [t1] [t2] ... [tood] ... [sadsada]
  Sample text [i8]
  [d9]
</html>

Python script must work with all strings and replace [%] -> some another string, for example:

<html>
  * * ... * ... *
  Sample text *
  *
</html>

What I did:

import re
import codecs

fullData = ''
for line in codecs.open(u'test.txt', encoding='utf-8'):
    line = re.sub("\[.*?\]", '*', line)
    fullData += line

print fullData

This code does exactly I described in sample. Thanks all.

+2  A: 

Looks like you need to parse a generic textfile, looking for that marker to replace it -- the fact that other text outside the marker is HTML, at least from the way you phrased your task, does not seem to matter.

If so, and what you want is to replace every occurrence of [%anytext%] with loremipsum, then a simple:

thenew = theold.replace('[%anytext%]', 'loremipsum')

will serve, if theold is the original string containing the file's text -- now thenew is a new string with all occurrences of that marker replaced - no need for regex, BS or anything else.

If your task is very different from this, pls edit your Question to explain it in more detail!-)

Alex Martelli
the task came from a prior answer: http://stackoverflow.com/questions/2580343/removing-template-string-from-html-file-with-javascript
msw
Yeah, JavaScript is not compatible with another needing, so we chose python for this.
Ockonal
Updated post with example.
Ockonal
@Alex: I love reading your posts, no matter what the topic. I always seem to learn something new -- in this case, lorem ipsum! Thanks!
unutbu
+2  A: 

Regex does the trick if you are needing to replace any text between "[%" and "%]".

The code would look something like this:

import re


newstring = re.sub("\[%.*?%\]",newtext,oldstring)

The regex used here is lazy so it would match everything between an occurrence of "[%" and the next occurrence of "%]". You could make it greedy by removing the question mark. This would match everything between the first occurrence of of "[%" and the last occurrence of "%]"

Hurpe