unicode - 在文件中搜索非 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 字符。
解决方案
见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
推荐阅读
- javascript - 从输入字段拍照并转换为base64
- django - 将用户模型中的 first_name、last_name 和 email 设置为字段中的默认值
- sql - 使用拆分的 T-SQL 分组
- python - 输出是数字列表而不是一个数字
- java - 具有该位置 [1] 的参数不存在;嵌套异常是 java.lang.IllegalArgumentException:具有该位置 [1] 的参数不存在
- python - 在 SQLAlchemy 中使用 selectinload 加载相关对象时的排序顺序
- asp.net - 要并排渲染的 CommandField ImageButtons
- java - 为什么在减少之前需要对分区进行排序?
- javascript - 如何从 webpack 输出中获取 bundle.js 函数
- c# - 不使用 ironpython 从 C# 运行 Python 文件的另一个解决方案