【问题标题】:python3 TypeError: 'bytes' object is not callablepython3 TypeError:'bytes'对象不可调用
【发布时间】:2018-10-22 06:30:50
【问题描述】:

我的代码:

 for i in range(data.num_nodes):
        if embed[i]:
            # print embed[i]
            tmp = np.sum(embed[i], axis=0) / len(embed[i])
            file.write(' '.join(map(str.encode("utf-8"), tmp)) + '\n')
        else:
            file.write('\n')

但是,当我运行代码时,我得到:

file.write(' '.join(map(str.encode("utf-8"), tmp)) + '\n')
`TypeError: 'bytes' object is not callable`

当我把代码改成这样时:

  for i in range(data.num_nodes):
        if embed[i]:
            # print embed[i]
            tmp = np.sum(embed[i], axis=0) / len(embed[i])
            file.write(' '.join(map(str, tmp)) + '\n')
        else:
            file.write('\n')

我收到此错误:

TypeError: a bytes-like object is required, not 'str'

【问题讨论】:

  • 也许这与str.encode("utf-8") 不是函数有关...?请提供有关您要执行的操作的更多说明。
  • 我们无法通过给定的工作弄清楚我们的问题到底是什么。所以请提供您的完整代码,以便我们回答您
  • 好的,如果我了解您要做什么(以及问题所在),我认为这可能会有所帮助:stackoverflow.com/a/16957257/5462551

标签: python python-3.x


【解决方案1】:

map 需要一个函数对象作为它的第一个参数,而使用str.encode("utf-8") 你实际上调用str.encode 并使用'utf-8' 作为第一个参数并将字符串'utf-8' 编码为字节,所以当map在第一个参数中调用该函数,它会失败,因为它实际上是一个字符串。

您应该使用functools.partialstr.encode 传递给map str.encode 作为函数对象,其中encoding 参数预先填充了您所需的编码:

from functools import partial
file.write(' '.join(map(partial(str.encode, encoding='utf-8'), tmp)) + '\n')

但由于str.encodeencoding 参数的默认值为'utf-8',您可以通过将str.encode 直接传递给map 来使map 使用str.encode 的默认值:

file.write(' '.join(map(str.encode, tmp)) + '\n')

但是由于您真正想要做的是将要传递给file.write 的整个字符串转换为字节,包括' ''\n',它们是字符串而不是字节,您应该编码连接子字符串并与'\n'连接后的整个字符串:

file.write((' '.join(tmp) + '\n').encode())

由于您的tmp 不是字符串列表,而是numpy.float32 对象的列表,因此您应该在加入之前先将它们映射到字符串:

file.write((' '.join(map(str, tmp)) + '\n').encode())

【讨论】:

  • 我使用 :file.write(' '.join(list(map(str.encode, tmp))) + '\n') 但是,TypeError 发生:描述符 'encode' 需要一个 ' str' 对象,但收到一个 'numpy.float32'
  • 我明白了。请参阅我更新的答案中的最后一个解决方案。
【解决方案2】:

做:

file.write(' '.join(map(str.encode, tmp)) + '\n')

代替:

file.write(' '.join(map(str.encode("utf-8"), tmp)) + '\n')

因为str.encode 需要一个字符串参数,这是因为默认它已经是utf-8 编码

【讨论】:

  • str.encode 不是函数吗?它期待一个bytes 对象。所以理论上,你不应该这样做bytes(str, 'UTF-8') 来转换它吗?这是不知道str 是什么。
猜你喜欢
  • 2015-02-14
  • 1970-01-01
  • 2019-01-05
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
相关资源
最近更新 更多