Python对字符串编码与解码

from urllib.parse import quote, unquote

# 修改字符串编码
text = "http://zhishi.me/zhwiki/resource/%E5%90%95%E9%BE%99%E5%85%89"
# print(unquote(""""\u897f\u683c\u8bfa\u745e\u4e9a\u516c\u5bd3\u9152\u5e97" ."""))
print(text.encode('raw_unicode_escape').decode())


# url 解码 类似:http://zhishi.me/zhwiki/resource/%E5%90%95%E9%BE%99%E5%85%89
# 使用 unquote
def url_parse_file2unicode(src_path, new_file, infile):
    open_diff = open('%s\%s' % (src_path, infile), 'r', encoding='utf-8')
    line_num = open_diff.readlines()

    with open('%s\%s' % (src_path, new_file), 'w', encoding='utf-8') as file:
        for line in line_num:
            file.write(unquote(line))

    file.close()
    open_diff.close()


# url 编码
# 使用 quote ,将其变为类似于:http://zhishi.me/zhwiki/resource/%E5%90%95%E9%BE%99%E5%85%89
def url_parse_file(src_path, new_file, infile):
    open_diff = open('%s\%s' % (src_path, infile), 'r', encoding='utf8')
    line_num = open_diff.readlines()

    with open('%s\%s' % (src_path, new_file), 'w', encoding='utf8') as file:
        for line in line_num:
            file.write(quote(line))


# 类似:http://cndbpedia/ontology/\u5b9e\u4f53\u540d\u79f0
# 使用 unicode-escape
def decode_parse_file(src_path, new_file, infile):
    open_diff = open('%s\%s' % (src_path, infile), 'r')
    line_num = open_diff.readlines()
    open_diff.readline()

    with open('%s\%s' % (src_path, new_file), 'w', encoding='utf-8') as file:
        for line in line_num:
            # 先编码再解码
            file.write(unquote(line.encode().decode(encoding='unicode-escape')))


if __name__ == '__main__':
    src_path = "C:\\Users\\my\\Desktop\\NLP"
    infile = "cndbpediaDump_26.nt"
    new_file = "new_%s" % infile
    # 如果含有 % ,则使用 unquote
    if open('%s\%s' % (src_path, infile), 'r', encoding='utf-8').readline().find("%") > 0:
        url_parse_file2unicode(src_path, new_file, infile)
    # 如果没有 % ,则使用 unicode-escape
    else:
        decode_parse_file(src_path, new_file, infile)

总结

str.encode() 把一个字符串转换为其 raw bytes 形式

bytes.decode()raw bytes 转换为其字符串形式

遇到类似的编码问题时,先 text 是什么类型,如果 type(text) is bytes ,那么

text.decode('unicode-escape')

如果 type(text) is str ,那么(将 Unicode 的内存编码值进行存储,读取文件时反向转换回来。这里就采用了 unicode-escape 的方式)

text.encode().decode('unicode-escape')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值