gpt4 book ai didi

python - 将非 UTF-8 字符转换为 UTF-8

转载 作者:太空宇宙 更新时间:2023-11-04 08:21:46 25 4
gpt4 key购买 nike

我的 Linux 系统上有一些文件。这些文件名可以是其他 un_eng-utf8。我想将它们从非 utf8 字符转换为 utf-8 字符。我如何使用 C 库函数或 Python 脚本来做到这一点。

最佳答案

如果您知道用于对文件名进行编码的字符编码:

unicode_filename = bytestring_filename.decode(character_encoding)
utf8filename = unicode_filename.encode('utf-8')

如果您不知道字符编码,那么在一般情况下没有办法在不丢失数据的情况下进行转换——“非 utf8”不够具体,例如,如果您的文件名包含 b'\xae' 字节然后它可以根据文件名编码进行不同的解释 - 它是 u'®' in cp1252 编码,但相同的字节 表示cp437 中的u'«'chardet 等模块可让您猜测字符编码,但这只是猜测 -- "There Ain't No Such Thing as Plain Text."

关于python - 将非 UTF-8 字符转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33100182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com