gpt4 book ai didi

python - 如何检测文件是否使用 UTF-8 编码?

转载 作者:太空狗 更新时间:2023-10-29 20:36:45 26 4
gpt4 key购买 nike

有没有办法在 Python 中识别文本文件是否为 UTF-8?

我真的很想知道文件是否是 UTF-8。我不需要检测其他编码。

最佳答案

您在评论中提到您只需要检测 UTF-8。如果您知道替代方案仅包含单字节编码,那么就有一个通常有效的解决方案。

如果您知道它是 UTF-8 或单字节编码(如 latin-1),请尝试先用 UTF-8 打开它,然后再用其他编码打开它。如果该文件仅包含 ASCII 字符,它最终将以 UTF-8 打开,即使它原本打算作为其他编码。如果它包含任何非 ASCII 字符,这几乎总是会正确地检测到两者之间的正确字符集。

try:
# or codecs.open on Python <= 2.5
# or io.open on Python > 2.5 and <= 2.7
filedata = open(filename, encoding='UTF-8').read()
except:
filedata = open(filename, encoding='other-single-byte-encoding').read()

最好的办法是使用 chardet package from PyPI ,直接或通过 BeautifulSoup 的 UnicodeDamnit:

chardet 1.0.1

Universal encoding detector

Detects:

  • ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants)
  • Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese)
  • EUC-JP, SHIFT_JIS, ISO-2022-JP (Japanese)
  • EUC-KR, ISO-2022-KR (Korean)
  • KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic)
  • ISO-8859-2, windows-1250 (Hungarian)
  • ISO-8859-5, windows-1251 (Bulgarian)
  • windows-1252 (English)
  • ISO-8859-7, windows-1253 (Greek)
  • ISO-8859-8, windows-1255 (Visual and Logical Hebrew)
  • TIS-620 (Thai)

Requires Python 2.1 or later

但是,有些文件在多种编码中都是有效的,所以 chardet 并不是万能的。

关于python - 如何检测文件是否使用 UTF-8 编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10156090/

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