【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)UnicodeEncodeError:“ascii”编解码器无法对位置 0-2 中的字符进行编码:序数不在范围内(128)
【发布时间】:2016-12-26 09:26:12
【问题描述】:

我正在尝试编写一个相当复杂的 Python 程序,但基本上已经完成了。我在一个小细节上遇到了麻烦。

有问题的代码部分是这样的:

newData = kmeans.sampleNewData(200, means, covariances, priors)

newData = newData.astype(str)
...loops and logic and stuff...
newData[i, j] = columnsList[j][(indexList[j]).index(closestFit)]

基本上,newData 是一个大小为 200 x 4 的 numpy 矩阵,其中填充了浮点类型的数字。然后我使用astype 方法将它们转换为字符串。

然后我尝试将这个columnsList[j][(indexList[j]).index(closestFit)](它是一些字符串)放入newData 的条目中。

问题是columnsList[j][(indexList[j]).index(closestFit)]不一定是英文。例如,它可以是希伯来语。在这种情况下 - 我收到错误

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

值得注意的是,我写了# -*- coding: utf-8 -*-,所以我们用utf-8编码,当我打印columnsList[j][(indexList[j]).index(closestFit)]时,它确实打印了正确的值。所以我们可以打印它。但由于某种原因,我无法将其放入newData 矩阵中。

【问题讨论】:

  • astype(str) 可能正在创建字节字符串数组。 dtype 是什么。那是ASCII。您可能需要指定 unicode dtype 来保存这些额外的字符。

标签: python numpy encoding


【解决方案1】:

当您尝试将某些字符串类型转换为字节时,编码是一种操作。看来,你的 columnsList[j][(indexList[j]).index(closestFit)] 包含 Unicode 字符串,所以试试

newData[i, j] = columnsList[j][(indexList[j]).index(closestFit)].encode('utf-8')

改为。

【讨论】:

  • 给我错误“AttributeError: 'float' object has no attribute 'encode'”
  • 首先我们需要弄清楚我们可以拥有哪些类型的数据。如果我们有浮点数,而不是 Unicode 字符串,当然会有错误。因此,在进行编码或任何操作之前,请尝试验证您的单元格值的类型。您那里可能拥有哪些类型的数据?
  • 好吧,当我打印 columnsList[j][(indexList[j]).index(closestFit)] 时,它会输出“פרו”,这是一串希伯来文文本,意思是秘鲁国家。当我尝试打印其类型时,我收到错误“Unicode 对象没有属性类型”
  • 如何打印类型?试试 print(type(columnsList[j][(indexList[j]).index(closestFit)))。我想您的数据有多种类型。 Unicode、str、float 等等。
猜你喜欢
  • 2012-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多