Re: Strip HTML tags?

Discussion in 'Python' started by EP, Dec 14, 2003.

  1. EP

    EP Guest


    >Hello,
    >
    >I was wondering what would be the easiest way to strip away HTML tags from
    >a string?
    >
    >Or how would I remove everything between < and > also the < , > as well
    >using regex?



    I'm a newbie, but here's a way I did it:

    ## compile regular expressions for HTML tags... I did a separate one for
    line breaks
    htmltags=re.compile(r'<p.*?>|</p>|<tr>|</tr>|<td.*?>|</td>|<a.*?>|</a>|<i>|</i>|<b>|</b>|<hr.*?>')
    linebreaks=re.compile(r'<br>|<br/>')
    ## not shown: some lines to input or iterate files go here; then you get
    the html file as a string:
    wwwf=open(nextfile, 'r')
    strng=wwwf.read()
    wwwf.close()
    ## execute some regular expression methods
    ## first one substitutes empty single quotes for known html tags
    nohtml=htmltags.sub('',strng)
    ## this one splits the string into lines on <br> or <br /> consuming the
    html tag in the process
    textlines=linebreaks.split(nohtml)
    ## you could then print it to stdout or file
    for line in textlines:
    print line

    OK, on second thought it was probably not the easiest way, which is what
    you asked; but it wasn't hard and I understood how it worked. :)
    EP, Dec 14, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Daniel M. Hendricks

    Regex to strip evil HTML tags

    Daniel M. Hendricks, Apr 10, 2005, in forum: ASP .Net
    Replies:
    2
    Views:
    6,001
    vMike
    Apr 11, 2005
  2. Fazer

    Strip HTML tags?

    Fazer, Dec 14, 2003, in forum: Python
    Replies:
    8
    Views:
    921
    Fazer
    Dec 16, 2003
  3. Laphan
    Replies:
    1
    Views:
    97
    Anthony Jones
    Jun 18, 2006
  4. Aquila
    Replies:
    35
    Views:
    430
    Mathieu Bouchard
    Mar 31, 2005
  5. yelipolok
    Replies:
    4
    Views:
    232
    John W. Krahn
    Jan 27, 2010
Loading...

Share This Page