正则表达式从Python中删除字符串中的html标记

时间:2011-08-29 06:43:38

标签: python regex string substring

我使用以下代码从RSS Feed中获取我的资源:

try:
    desc = item.xpath('description')[0].text
    if date is not None:
        desc =date +"\n"+"\n"+desc
except:
    desc = None

但有时描述中包含RSS feed中的html标签,如下所示:

  

这是一篇文章

< img src =“http:// imageURL”alt =“”/>

在显示内容时,我不希望在页面上显示任何HTML标记。是否有正则表达式来删除HTML标记。

3 个答案:

答案 0 :(得分:1)

尝试:

pattern = re.compile(u'<\/?\w+\s*[^>]*?\/?>', re.DOTALL | re.MULTILINE | re.IGNORECASE | re.UNICODE)
text = pattern.sub(u" ", text)

答案 1 :(得分:1)

快速而肮脏的方式:

def remove_html_tags(text):
    pattern = re.compile(r'<.*?>')
    return pattern.sub('', text)

但是对于更强大的解决方案,我建议您查看Beautiful Soup

答案 2 :(得分:1)

如果不使用正则表达式,有一种简单的方法。这是一个强大的解决方案:

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

这个想法在这里解释:http://youtu.be/2tu9LTDujbw

您可以在此处看到它:http://youtu.be/HPkNPcYed9M?t=35s

PS - 如果您对该课程感兴趣(关于使用python进行智能调试),我会给你一个链接:http://www.udacity.com/overview/Course/cs259/CourseRev/1。免费!

欢迎你! :)