Skip to main content
 首页 » 编程设计

python之使用 Python 3 删除 "characters with encodings larger than 3 bytes"

2024年09月07日9pander-it

我想删除编码大于 3 个字节的字符。 因为当我将我的 CSV 数据上传到 Amazon Mechanical Turk 系统时,它要求我这样做。

Your CSV file needs to be UTF-8 encoded and cannot contain characters with encodings larger than 3 bytes. For example, some non-English characters are not allowed (learn more).

为了克服这个问题, 我想制作一个 filter_max3bytes 函数来删除 Python3 中的那些字符。

x = 'below ð\x9f~\x83,' 
y = remove_max3byes(x)  # y=="below ~," 

然后我将在将函数保存到 UTF-8 编码的 CSV 文件之前应用该函数。

This post与我的问题有关,但他们使用 python 2 并且该解决方案对我不起作用。

谢谢!

请您参考如下方法:

您的字符串中的所有字符在 UTF-8 中似乎都不占用 3 个字节:

x = 'below ð\x9f~\x83,' 

无论如何,如果有的话,删除它们的方法是:

filtered_x = ''.join(char for char in x if len(char.encode('utf-8')) < 3) 

例如(有这样的字符):

>>> x = 'abcd漢字efg' 
>>> ''.join(char for char in x if len(char.encode('utf-8')) < 3) 
'abcdefg' 

顺便说一句,您可以通过执行以下操作来验证您的原始字符串没有 3 字节编码:

>>> for char in 'below ð\x9f~\x83,': 
...     print(char, [hex(b) for b in char.encode('utf-8')]) 
... 
b ['0x62'] 
e ['0x65'] 
l ['0x6c'] 
o ['0x6f'] 
w ['0x77'] 
  ['0x20'] 
ð ['0xc3', '0xb0'] 
  ['0xc2', '0x9f'] 
~ ['0x7e'] 
  ['0xc2', '0x83'] 
, ['0x2c'] 

编辑:一个疯狂的猜测

我相信 OP 问错了问题,问题实际上是字符是否可打印。我假设任何 Python 显示为 \x<number>不可打印,因此此解决方案应该有效:

x = 'below ð\x9f~\x83,' 
filtered_x = ''.join(char for char in x if not repr(char).startswith("'\\x")) 

结果:

'below ð~,'