首页 > 解决方案 > 在文件中搜索非 unicode 字符

问题描述

我有一个文本块(从 db 中提取),我想找到非 unicode 字符,因为在代码的某些部分(python 3.6),当我将值转换为时,str我得到以下ValueError: character U+ffffffc2 is not in range [U+0000; U+10ffff]

所以如果我能找到非 unicode 字符,我可以决定如何处理它们。我绝对不想用其他东西代替它们。

我找到了如何在文件中查找非 ascii 字符,grep --color='auto' -P -n '[^\x00-\x7F]' file_name.txt但我不确定这是否也给了我非 unicode 字符。

标签: unicodecharacter-encoding

解决方案


http://p3rl.org/Encode#coderef-for-CHECK

# contains U+ffffffc2 encoded in UTF-8
› hex nonunicodefile
0000  61 62 63 fe 83 bf bf bf  bf 82 78 79 7a           abc..... ..xyz

› perl -MEncode -lne'
    # replace junk with empty string
    my $line = decode "UTF-8", $_, sub { "" };
    print encode "UTF-8", $line;
' < nonunicodefile
abcxyz

推荐阅读