首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >[python][原创]对&#编码转成中文的3种方法

[python][原创]对&#编码转成中文的3种方法

作者头像
云未归来
发布2025-07-20 11:06:23
发布2025-07-20 11:06:23
11700
代码可运行
举报
运行总次数:0
代码可运行

第一种:html模块,强烈推荐

代码语言:javascript
代码运行次数:0
运行
复制
import html
print(html.unescape('中国'))

第二种:自定义函数

代码语言:javascript
代码运行次数:0
运行
复制
#第二种方法
def convert_unicode(text):
    text = text.replace('&#', '')
    text = [i for i in text.split(';') if i]
    text = [hex(int(i)) for i in text]
    text = [i.replace('0x', '') for i in text]
    string = ''
    flag = '\\u'
    for i in text:
        string += flag + format(i, '0>4s')
    return string.encode('utf-8').decode('unicode-escape')


a = '缝头印'
print(convert_unicode(a))

第三种:使用HTMParse模块

代码语言:javascript
代码运行次数:0
运行
复制
#第三种方法
import HTMLParser
s = '【试呼】'
h = HTMLParser.HTMLParser()
print(h.unescape(s))

但是第三种方法不是pip install HTMLParser就完了运行会报错,可以参考博客

python3 解决&#开头的Unicode编码的字符串问题的通用方法_&#9776 python_zhaojiafu666的博客-CSDN博客

由于麻烦点因此不推荐第三种方法。

最后还有人需要把中文转成&#格式这里我写个一个函数,大家可以试试

代码语言:javascript
代码运行次数:0
运行
复制
a = '缝头印'
b = '缝头印'


def chinese2html(chars):
    all = chars.encode('unicode-escape').decode()
    lines = all.split('\\u')[1:]
    result = ''
    for line in lines:
        result += "&#" + str(int(line, 16)) + ';'
    return result


res = chinese2html(b)
print(res)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档