【发布时间】:2020-01-28 16:17:17
【问题描述】:
我正在使用 Python 3.7。如何从字符串中删除所有非 UTF-8 字符?我尝试在下面使用“lambda x: x.decode('utf-8','ignore').encode("utf-8")”
coop_types = map(
lambda x: x.decode('utf-8','ignore').encode("utf-8"),
filter(None, set(d['type'] for d in input_file))
)
但这会导致错误...
Traceback (most recent call last):
File "scripts/parse_coop_csv.py", line 30, in <module>
for coop_type in coop_types:
File "scripts/parse_coop_csv.py", line 25, in <lambda>
lambda x: x.decode('utf-8','ignore').encode("utf-8"),
AttributeError: 'str' object has no attribute 'decode'
如果您有一种通用的方法可以从字符串中删除所有非 UTF8 字符,那就是我正在寻找的全部内容。
【问题讨论】:
-
你先编码
x,然后解码。str.encode接受一个 Unicode 字符串并生成它的 UTF-8 编码。bytes.decode接受一个字符串并尝试将其解释为一种编码以生成str对象。 -
您能否举例说明
str实例中的非UTF-8 字符是什么?您是指代理代码点吗?
标签: python python-3.x utf-8 decode encode