Cam*_*amW 43
您可以使用记事本打开文件,然后转到文件 - >另存为.在"保存"按钮旁边会有一个编码下拉列表,将在那里选择文件的当前编码.
小智 28
在Linux系统中,您可以使用file命令.它将提供正确的编码
样品:
file blah.csv
Run Code Online (Sandbox Code Playgroud)
输出:
blah.csv: ISO-8859 text, with very long lines
Run Code Online (Sandbox Code Playgroud)
小智 18
如果使用Python,则只需使用print()函数来检查csv文件的编码。例如:
with open('file_name.csv') as f:
print(f)
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
<_io.TextIOWrapper name='file_name.csv' mode='r' encoding='utf8'>
Run Code Online (Sandbox Code Playgroud)
使用chardet https://github.com/chardet/chardet?文档简短易读)。
安装python,然后pip install chardet,最后使用命令行命令。
我在 GB2312 下测试过,非常准确。(确保您至少有几个字符,只有 1 个字符的样本可能很容易失败)。
file 如您所见,并不可靠。
您还可以使用 python chardet 库
# install the chardet library
!pip install chardet
# import the chardet library
import chardet
# use the detect method to find the encoding
# 'rb' means read in the file as binary
with open("test.csv", 'rb') as file:
print(chardet.detect(file.read()))
Run Code Online (Sandbox Code Playgroud)
小智 5
或者您可以在 python 控制台或 Jupyter Notebook 中执行:
import csv
data = open("file.csv","r")
data
Run Code Online (Sandbox Code Playgroud)
您将看到有关数据对象的信息,如下所示:
<_io.TextIOWrapper name='arch.csv' mode='r' encoding='cp1250'>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它包含编码信息。
CSV 文件没有指示编码的标头。
你只能通过查看来猜测:
2021年,表情符号被广泛使用,但很多导入工具却导入失败。上面的答案中经常推荐该chardet库,但该库不能很好地处理表情符号。
icecream = ''
import csv
with open('test.csv', 'w') as f:
wf = csv.writer(f)
wf.writerow(['ice cream', icecream])
import chardet
with open('test.csv', 'rb') as f:
print(chardet.detect(f.read()))
{'encoding': 'Windows-1254', 'confidence': 0.3864823918622268, 'language': 'Turkish'}
Run Code Online (Sandbox Code Playgroud)
这会在尝试使用此编码读取文件时出现 UnicodeDecodeError。
Mac 上的默认编码是 UTF-8。它被明确地包含在这里,但这甚至不是必要的......但在 Windows 上可能是这样。
with open('test.csv', 'r', encoding='utf-8') as f:
print(f.read())
ice cream,
Run Code Online (Sandbox Code Playgroud)
该file命令也发现了这个
file test.csv
test.csv: UTF-8 Unicode text, with CRLF line terminators
Run Code Online (Sandbox Code Playgroud)
我在 2021 年的建议是,如果自动检测出错:UTF-8在求助于chardet.
| 归档时间: |
|
| 查看次数: |
99338 次 |
| 最近记录: |