在Python中使用正则表达式去除字符串中的HTML标签

3 投票
3 回答
3031 浏览
提问于 2025-04-17 00:30

我正在使用以下代码从RSS源获取我的结果:

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

但是有时候,描述中会包含一些HTML标签,像下面这样:

这是示例文本

< img src="http://imageURL" alt="" />

在显示内容时,我不想让页面上出现任何HTML标签。有没有什么正则表达式可以用来去掉这些HTML标签呢?

3 个回答

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

顺便说一下,如果你对这门课程(关于用Python进行智能调试)感兴趣,这里有个链接:http://www.udacity.com/overview/Course/cs259/CourseRev/1。这门课是免费的!

不客气!:)

1

快速简单的方法:

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

不过,如果你想要一个更可靠的解决方案,我建议你看看 Beautiful Soup

1

试试这个:

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

撰写回答