为什么 ISO 8859-1 嵌入到 unicode Python 字符串中?

Why is ISO 8859-1 embedded into unicode Python strings?

所以我有一个 CSV 文件。

当我运行 file --mime-encoding file.csv 时它说它使用UTF-8。

但是,当我读取 Python pandas DataFrame 中的文件并开始查看字符串时,其中一些包含 \xa0 (在 Latin1 中是不间断的 space ( ISO 8859-1)).

此文件包含来自不同网站的信息。

这怎么可能?为什么它们没有显示为不间断 space 以及为什么它们在写入看似为 UTF-8 的文件之前没有正确编码?

How is that possible

文件只是一系列字节。一个文件完全有可能包含不同编码的字节串。

why are they not displayed as non-breaking space

显示在哪里?它们显示为 \xa0.

why were they not encoded properly before being written to a file that appears to be UTF-8?

您没有提及 CSV 的来源,因此无法确定。

很可能,您的 CSV 包含来自具有不同编码的来源的数据。您可能需要猜测文件中每一行的编码,而不是整个文件。 chardet 包可以帮助您猜测正确的编码,但这只是猜测。