Regular Expression to remove html tags from a string in Python
I am fetching my resut from a RSS feed using following code:
try:
desc = item.xpath('description')[0].text
if date is not None:
desc =date +"\n"+"\n"+desc
except:
desc = None
But sometimes the description contains html tags inside RSS feed as below:
This is开发者_运维知识库 samle text
< img src="http://imageURL" alt="" />
While displaying the content I do not want any HTML tags to be displayed on page. Is there any regular expression to remove the HTML tags.
Try:
pattern = re.compile(u'<\/?\w+\s*[^>]*?\/?>', re.DOTALL | re.MULTILINE | re.IGNORECASE | re.UNICODE)
text = pattern.sub(u" ", text)
The quick and dirty way:
def remove_html_tags(text):
pattern = re.compile(r'<.*?>')
return pattern.sub('', text)
But for a more robust solution, I'd recommend looking into Beautiful Soup.
There's a simple way to this without using regex. It's a robust solution:
def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif (c == '"' or c == "'") and tag:
quote = not quote
elif not tag:
out = out + c
return out
The idea is explained here: http://youtu.be/2tu9LTDujbw
You can see it working here: http://youtu.be/HPkNPcYed9M?t=35s
PS - If you're interested in the class(about smart debugging with python) I give you a link: http://www.udacity.com/overview/Course/cs259/CourseRev/1. It's free!
You're welcome! :)
精彩评论