使用正则表达式删除HTML实体并提取文本内容。

bluesky3月前 ⋅ 44 阅读

ChatGPT的回答仅作参考:

以下是Python代码示例:

```python
import re

def remove_html_entities(text):
    # 删除HTML实体
    text = re.sub(r"&[a-zA-Z]+;", "", text)
    return text

def extract_text_from_html(html):
    # 提取文本内容
    text = re.sub(r"<.*?>", "", html)
    text = remove_html_entities(text)
    return text
```

使用示例:

```python
html = "<p>This is <b>bold</b> text with an &amp; entity.</p>"
text = extract_text_from_html(html)
print(text)  # 输出:This is bold text with an & entity.
```

解释:

- `re.sub(r"<.*?>", "", html)`:使用正则表达式删除所有HTML标签。
- `remove_html_entities(text)`:使用正则表达式删除所有HTML实体。

全部评论: 0

    相关推荐