Xiè*_*léi 86 linux encoding batch
有许多纯文本文件以不同的字符集编码。
我想将它们全部转换为 UTF-8,但在运行 iconv 之前,我需要知道其原始编码。大多数浏览器都有Auto Detect
编码选项,但是我无法一一检查这些文本文件,因为太多了。
只有知道原始编码,然后我才能将文本转换为iconv -f DETECTED_CHARSET -t utf-8
.
是否有任何实用程序可以检测纯文本文件的编码?它不必是 100% 完美的,我不介意在 1,000,000 个文件中是否有 100 个文件被错误转换。
use*_*686 76
试试在 PyPI 上可用的chardet Python 模块:
pip install chardet
Run Code Online (Sandbox Code Playgroud)
然后运行chardetect myfile.txt
。
Chardet 基于Mozilla 使用的检测代码,因此它应该给出合理的结果,前提是输入文本足够长以进行统计分析。请阅读项目文档。
正如评论中提到的,它很慢,但一些发行版还提供了原始 C++ 版本,正如 @Xavier 在https://superuser.com/a/609056 中发现的那样。某处也有 Java 版本。
小智 39
我会使用这个简单的命令:
encoding=$(file -bi myfile.txt)
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想要实际的字符集(如utf-8
):
encoding=$(file -b --mime-encoding myfile.txt)
Run Code Online (Sandbox Code Playgroud)
小智 31
在基于 Debian 的 Linux 上,uchardet包 ( Debian / Ubuntu ) 提供了一个命令行工具。请参阅下面的包装说明:
universal charset detection library - cli utility
.
uchardet is a C language binding of the original C++ implementation
of the universal charset detection library by Mozilla.
.
uchardet is a encoding detector library, which takes a sequence of
bytes in an unknown character encoding without any additional
information, and attempts to determine the encoding of the text.
.
The original code of universalchardet is available at
http://lxr.mozilla.org/seamonkey/source/extensions/universalchardet
.
Techniques used by universalchardet are described at
http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html
Run Code Online (Sandbox Code Playgroud)