【问题标题】:How to solve python 'utf-8' error?如何解决 python 'utf-8' 错误?
【发布时间】:2017-12-04 08:40:30
【问题描述】:

我试图在我的 python 3 终端中读取一个 6GB 的文件,但无法执行读取文件行。代码如下:

#define data directory

data_dir = 'C://Star/star_data/csv\Globe'

#read the review dataset
yelp = pd.read_csv(data_dir+'\star_data_python.csv')
X, y = star.data, star.target
X.shape

错误:

UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-4-bc09b45c73bb> in <module>()
      4 
      5 #read the review dataset
----> 6 yelp = pd.read_csv(data_dir+'\star_data_python.csv')
      7 X, y = star.data, star.target
      8 X.shape

可能是什么问题?谢谢

【问题讨论】:

  • 您在路径中同时使用了/\ ...如果您使用的是Windows,请仅在字符串前面使用/r,例如data_dir = r'C://Star/star_data/csv/Globe'
  • 如果不是路径问题,请尝试将,encoding='utf-8'添加到read_csv
  • #define data directory 我已将其更正为下面的行,但我仍然遇到相同的错误。 data_dir = r'C://Star/star_data/csv/Globe' #读取评论数据集 yelp = pd.read_csv(data_dir + '/star_data_python.csv')
  • 嗨@MugB,尝试将编码utf-8添加到您的csv文件中:pd.read_csv(data_dir+'\star_data_python.csv, encoding='utf-8')
  • pandas\parser.pyx in pandas.parser.TextReader.__cinit__ (pandas\parser.c:6086)() pandas\parser.pyx in pandas.parser.TextReader._get_header (pandas\parser. c:9266)() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe3 in position 2543: invalid continuation byte

标签: python python-3.x


【解决方案1】:

在您的路径前使用r,因为您使用的是 Windows:

例如

data_dir = r'C://Star/star_data/csv/Globe'

'r' 表示该字符串将被视为原始字符串,这意味着所有转义码都将被忽略。

尝试使用encoding='latin1'encoding='iso-8859-1'encoding='cp1252' 调用read_csv;这些是在 Windows 上找到的各种编码。

例如

full_path = data_dir + r'/star_data_python.csv'
pd.read_csv(full_path, encoding='latin1')

有用的 SO 答案列表:

【讨论】:

    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多