How to detect the encoding of a text file with Python?
Python 中有一个有用的包 - chardet,它有助于检测文件中使用的编码。实际上,没有程序可以 100% 确信使用了哪种编码 - 这就是为什么 chardet 以最高概率对文件进行编码的原因。Chardet 可以检测以下编码:
ASCII、UTF-8、UTF-16(2 种变体)、UTF-32(4 种变体)
Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (繁体中文和简体中文)
EUC-JP, SHIFT_JIS, CP932, ISO-2022-JP (日语)
EUC-KR, ISO-2022-KR(韩语)
KOI8-R, 麦西里尔文, IBM855, IBM866, ISO-8859-5, windows-1251 (西里尔文)
ISO-8859-2, 窗口-1250 (匈牙利语)
ISO-8859-5, 窗口-1251 (保加利亚语)
窗口-1252 (英语)
ISO-8859-7, 视窗-1253 (希腊文)
ISO-8859-8, windows-1255 (视觉和逻辑希伯来语)
TIS-620 (泰语)
您可以使用 pip 命令安装 chardet:
pip install chardet
之后,您可以在命令行中使用 chardet:
% chardetect somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
或者在 Python 中:
import chardet
rawdata = open(file, "r").read()
result = chardet.detect(rawdata)
charenc = result['encoding']
How to detect the encoding of a text file with Deno?
import { detectEncoding } from "https://dev.jspm.io/char-encoding-detector@0.0.9";
const file = "ex2022.txt";
const text = await Deno.readFile(file);
const encoding = detectEncoding(text);
const decoder = new TextDecoder(encoding);
const correct = decoder.decode(text);
console.log(correct);