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

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

import html
print(html.unescape('中国'))

第二种:自定义函数

#第二种方法
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模块

#第三种方法
import HTMLParser
s = '【试呼】'
h = HTMLParser.HTMLParser()
print(h.unescape(s))

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

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

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

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

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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FL1623863129

你的打赏是我写文章最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值