当前位置:首页 > python > 正文内容

python 字符串里有中文与html代码,怎么去掉html代码

zhangsir3年前 (2023-03-29)python232

你可以使用Python的内置字符串操作和正则表达式来去除HTML代码。以下是一个示例代码,它将删除字符串中的所有HTML标记和Unicode字符:

import re
# 字符串示例
my_string = "这是一个 <b>示例</b> 字符串,其中包含<p>一些</p> HTML 代码和中文字符 &#8211; 删除它们!"
# 删除HTML标记和Unicode字符
no_tags = re.sub('<[^<]+?>', '', my_string)  # 删除HTML标记
no_unicode = no_tags.encode('ascii', 'ignore').decode('utf-8')  # 删除Unicode字符
print(no_unicode)
输出结果将是:
这是一个 示例 字符串,其中包含一些 HTML 代码和中文字符  删除它们!

这个示例代码使用了Python的re模块来删除HTML标记。正则表达式 <[^<]+?> 表示匹配任何以 < 开头、以 > 结尾的字符串,其中 [^<]+ 表示匹配除了 < 之外的任何字符,+ 表示至少匹配一个字符。encode 和 decode 函数是用来删除Unicode字符的。


zhangsir版权y1防采集https://mianka.xyz

扫描二维码推送至手机访问。

版权声明:本文由zhangsir or zhangmaam发布,如需转载请注明出处。

本文链接:https://mianka.xyz/post/161.html

分享给朋友:

“python 字符串里有中文与html代码,怎么去掉html代码” 的相关文章

Python post请求报错 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

Python用post方式请求接口数据的时候,报错:Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported这是由于没有设置 Content-Typ...

如何向python 列表中添加元素

Python添加元素有三种方法:append、extend、insertappend:向列表添加元素,添加到尾部实例:list=[“my”,“name”,“is”,“mark”,“age”,18] print(“添加前:”,list) list.append(“test”) print(“添加...

python 写入文件

一、读写txt文件1、打开txt文件Note=open('x.txt',mode='w',encoding='utf-8')函数=open(x.扩展名,mode=模式)模式种类:w      ...

Selenium添加Cookie来实现自动登录

Selenium添加Cookie来实现自动登录第一步获取你登录的cookie,以csdn为例from selenium import webdriver driver = webdriver.Chrome() driver.get('...

Python三方库ddddocr实现验证码识别

Python三方库ddddocr实现验证码识别环境要求python >= 3.8安装三方库pip install ddddocr -i https://pypi.tuna.tsinghua.edu.cn/simple参数说明:参数名参数类型默认值说明us...

使用pyautogui进行屏幕捕捉实现自动化操作

import pyautogui import time # # 获取基本信息 # # 屏幕大小 # size = pyautogui.size() # print(size) #&nbs...