如何检查文件是否有效UTF-8?

Ian*_*son 64 validation utf-8 internationalization

我正在处理一些应该是有效的UTF-8但不是的数据文件,这导致解析器(不受我的控制)失败.我想为UTF-8格式良好地添加预先验证数据的阶段,但我还没有找到帮助实现这一目标的实用程序.

在W3C上有一个Web服务似乎已经死了,我找到了一个仅用于Windows的验证工具,它报告了无效的UTF-8文件,但没有报告要修复的行/字符.

无论是我可以插入和使用的工具(理想情况是跨平台),还是我可以参与我的数据加载过程的ruby/perl脚本,我都会感到满意.

Tor*_*rek 87

你可以使用GNU iconv:

$ iconv -f UTF-8 your_file -o /dev/null; echo $?
Run Code Online (Sandbox Code Playgroud)

或者使用旧版本的iconv,例如在macOS上:

$ iconv -f UTF-8 your_file > /dev/null; echo $?
Run Code Online (Sandbox Code Playgroud)

如果文件可以成功转换,该命令将返回0,否则返回1.此外,它将打印出无效字节序列发生的字节偏移量.

编辑:不必指定输出编码,它将被假定为UTF-8.

  • 在较旧版本的iconv中,就像在OSX或fink上一样,没有-o标志.但是,重定向标准输出应始终有效. (15认同)
  • 更好的是,将stdout和stderr重定向到/ dev/null:`iconv -f UTF-8 your_file>/dev/null 2>&1; echo $?` (2认同)
  • “输出编码 [...] 将被假定为 UTF-8”与文档相矛盾,该文档说编码“默认为当前语言环境的编码”(GNU 手册页)。如果该编码不支持输入中的任何字符,即使输入是有效的 UTF-8,也会发出“无法转换”或“非法输入序列”错误。使用`iconv -f UTF-8 -t UTF-8 your_file > /dev/null` 来避免这些误报。 (2认同)

tzo*_*zot 9

使用python和str.encode |解码函数.

>>> a="????"
>>> a
'\xce\xb3\xce\xb5\xce\xb9\xce\xb1'
>>> b='\xce\xb3\xce\xb5\xce\xb9\xff\xb1' # note second-to-last char changed
>>> print b.decode("utf_8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 6: unexpected code byte
Run Code Online (Sandbox Code Playgroud)

抛出的异常在其.args属性中请求了信息.

>>> try: print b.decode("utf_8")
... except UnicodeDecodeError, exc: pass
...
>>> exc
UnicodeDecodeError('utf8', '\xce\xb3\xce\xb5\xce\xb9\xff\xb1', 6, 7, 'unexpected code byte')
>>> exc.args
('utf8', '\xce\xb3\xce\xb5\xce\xb9\xff\xb1', 6, 7, 'unexpected code byte')
Run Code Online (Sandbox Code Playgroud)


Rog*_*ahl 9

您可以使用isutf8moreutils集合.

$ apt-get install moreutils
$ isutf8 your_file
Run Code Online (Sandbox Code Playgroud)

在shell脚本中,使用--quiet开关并检查退出状态,对于有效的utf-8文件,该状态为零.

  • 对于mac os"brew install moreutils".https://rentes.github.io/unix/utilities/2015/07/27/moreutils-package/ (2认同)

ASh*_*lly 5

gnu iconv库怎么样?使用 iconv() 函数:“在输入中遇到无效的多字节序列。在这种情况下,它将 errno 设置为 EILSEQ 并返回 (size_t)(-1)。*inbuf 指向无效多字节序列的开头。 ”

编辑:哦 - 我错过了你想要脚本语言的部分。但是对于命令行工作,iconv实用程序也应该为您验证。