使用 Python 2/3 解析 ANSI 和 UTF-16LE 文件的最佳方法?

发布于 2024-07-19 00:34:29 字数 145 浏览 7 评论 0 原文

我有一组以 ANSI 或 UTF-16LE 编码的文件。 我希望 python 使用正确的编码打开文件。 问题是 ANSI 文件在使用 UTF-16le 编码时不会引发任何类型的异常,反之亦然。

有没有一种简单的方法可以使用正确的文件编码打开文件?

I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.

Is there a straightforward way to open up the files using the correct file encoding?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自由范儿 2024-07-26 00:34:29

使用 chardet 库来检测编码。

Use the chardet library to detect the encoding.

因为看清所以看轻 2024-07-26 00:34:29

您可以检查文件开头的 BOM检查是否是UTF。

然后相应地 unicode.decode (使用 标准编码)。

编辑
或者,也许,尝试 s.decode('ascii') 你的字符串(假设 s 是变量名)。 如果它抛出 UnicodeDecodeError,则将其解码为“utf_16_le”。

You can check for the BOM at the beginning of the file to check whether it's UTF.

Then unicode.decode accordingly (using one of the standard encodings).

EDIT
Or, maybe, try s.decode('ascii') your string (given s is the variable name). If it throws UnicodeDecodeError, then decode it as 'utf_16_le'.

风渺 2024-07-26 00:34:29

文件里有什么? 如果它是基于拉丁字母表的纯文本,则 UTF-16LE 文件的几乎所有其他字节都为零。 另一方面,在 windows-1252 文件中,我根本不希望看到任何零。 例如,这里是 windows-1252 中的 “Hello”

93 48 65 6C 6C 6F 94

...以及 UTF-16LE 中:

1C 20 48 00 65 00 6C 00 6C 00 6F 00 1D 20

除了大引号之外,每个字符都映射到相同的值,并添加尾随零字节。 事实上,对于 ISO-8859-1 字符集中的每个字符都是如此(windows-1252 扩展了 ISO-8859-1 以添加多个打印字符的映射(例如大引号),以替换范围 中的控制字符0x80..0x9F)。

如果您知道所有文件都是 windows-1252 或 UTF-16LE,则只需快速扫描零即可找出哪个是哪个。 chardet 如此缓慢和复杂是有充分理由的,但在这种情况下,我认为你可以摆脱快速和肮脏的做法。

What's in the files? If it's plain text in a Latin-based alphabet, almost every other byte the UTF-16LE files will be zero. In the windows-1252 files, on the other hand, I wouldn't expect to see any zeros at all. For example, here's “Hello” in windows-1252:

93 48 65 6C 6C 6F 94

...and in UTF-16LE:

1C 20 48 00 65 00 6C 00 6C 00 6F 00 1D 20

Aside from the curly quotes, each character maps to the same value, with the addition of a trailing zero byte. In fact, that's true for every character in the ISO-8859-1 character set (windows-1252 extends ISO-8859-1 to add mappings for several printing characters—like curly quotes—to replace the control characters in the range 0x80..0x9F).

If you know all the files are either windows-1252 or UTF-16LE, a quick scan for zeroes should be all you need to figure out which is which. There's a good reason why chardet is so slow and complex, but in this case I think you can get away with quick and dirty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文