gpt4 book ai didi

python - 在 Python 3 中,如何从字符串中删除所有非 UTF8 字符?

转载 作者:行者123 更新时间:2023-12-01 06:30:05 32 4
gpt4 key购买 nike

我正在使用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 字符的通用方法,这就是我所寻找的。

最佳答案

你从一个字符串开始。您无法解码 str(它已经是解码后的文本,您只能再次将其编码为二进制数据)。 UTF-8 几乎可以对任何有效的 Unicode 文本进行编码(这就是 str 存储的内容),因此这种情况应该不会出现太多,但如果您遇到 surrogate characters在您的输入中,您可以反转方向,更改:

x.decode('utf-8','ignore').encode("utf-8")

至:

x.encode('utf-8','ignore').decode("utf-8")

在其中对任何可编码的 UTF-8 内容进行编码,丢弃不可编码的内容,然后解码现在干净的 UTF-8 字节。

关于python - 在 Python 3 中,如何从字符串中删除所有非 UTF8 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952915/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com