栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python对字符串编码与解码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python对字符串编码与解码

from urllib.parse import quote, unquote

# 修改字符串编码
text = "http://zhishi.me/zhwiki/resource/%E5%90%95%E9%BE%99%E5%85%89"
# print(unquote(""""u897fu683cu8bfau745eu4e9au516cu5bd3u9152u5e97" ."""))
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/u5b9eu4f53u540du79f0
# 使用 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')
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/893205.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号