【问题标题】:UnicodeEncodeError :'charmap' codec can't encode character '\x85' in position 102: character maps to <undefined>UnicodeEncodeError :'charmap' 编解码器无法对位置 102 中的字符 '\x85' 进行编码:字符映射到 <undefined>
【发布时间】:2020-06-13 15:01:24
【问题描述】:

我正在尝试将数组保存在文本文件中,但出现 Unicode 错误

df_duplicate = df[df['is_duplicate'] == 1]
dfp_nonduplicate = df[df['is_duplicate'] == 0]

# Converting 2d array of q1 and q2 and flatten the array: like {{1,2},{3,4}} to {1,2,3,4}
p = np.dstack([df_duplicate["question1"], df_duplicate["question2"]]).flatten()
n = np.dstack([dfp_nonduplicate["question1"], dfp_nonduplicate["question2"]]).flatten()

print ("Number of data points in class 1 (duplicate pairs) :",len(p))
print ("Number of data points in class 0 (non duplicate pairs) :",len(n))

#Saving the np array into a text file
np.savetxt('train_p.txt', p, delimiter=' ', fmt='%s')
np.savetxt('train_n.txt', n, delimiter=' ', fmt='%s')`

我知道我需要将其更改为 utf-8 格式,但我无法理解如何处理此特定代码。 还是python的初学者

【问题讨论】:

  • savetxtencoding 参数吗?
  • 不,我不这么认为
  • 你为什么这么认为?你检查过文档吗?
  • 尝试添加 utf-8 和 unicode 新错误。 " NameError: 名称 'Unicode' 未定义
  • 尝试了一切还是同样的错误,我所做的一切都无法解决这个问题,请帮忙。

标签: python arrays pandas numpy


【解决方案1】:

从我通过将np.savetxt 放入搜索引擎中找到的文档:

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='n', header='', footer='', comments='# ', encoding=None)
    Save an array to a text file.

所以,是的,它确实有一个encoding 参数。那是您指定文件编码的地方。所以:

np.savetxt('train_p.txt', p, delimiter=' ', fmt='%s', encoding='utf-8')

也就是说:有问题的字符在您的文本中是一个非常奇怪的字符。这将有助于查看您的数据来自何处。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-03-26
  • 2018-07-30
  • 2021-01-27
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2017-11-07
相关资源
最近更新 更多