[英]python3 TypeError: 'bytes' object is not callable
My code: 我的代码:
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')
However, when I run code, I get: 但是,当我运行代码时,我得到:
file.write(' '.join(map(str.encode("utf-8"), tmp)) + '\n')
`TypeError: 'bytes' object is not callable`
When I change the code into this: 当我将代码更改为此:
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')
I get this error: 我收到此错误:
TypeError: a bytes-like object is required, not 'str'
Do: 做:
file.write(' '.join(map(str.encode, tmp)) + '\n')
Instead of: 代替:
file.write(' '.join(map(str.encode("utf-8"), tmp)) + '\n')
Because str.encode
needs a argument of a string and this works because default it's already utf-8
encoding 因为
str.encode
需要一个字符串参数,所以这有效,因为默认情况下它已经是utf-8
编码
map
expects a function object as its first argument, and with str.encode("utf-8")
you actually call str.encode
with 'utf-8'
as the first argument and literally encode the string 'utf-8'
to bytes, so when map
calls the function in its first argument, it would fail as it is actually a string. map
需要一个函数对象作为它的第一个参数,并且实际上使用str.encode("utf-8")
调用以'utf-8'
作为第一个参数的str.encode
并将字串'utf-8'
编码为字节,因此当map
在其第一个参数中调用该函数时,由于它实际上是一个字符串,因此它将失败。
You should use functools.partial
to pass str.encode
to map
str.encode
as a function object with the encoding
parameter pre-filled with your desired encoding: 您应该使用
functools.partial
传递str.encode
到map
str.encode
作为与函数对象encoding
参数预填充您所需的编码:
from functools import partial
file.write(' '.join(map(partial(str.encode, encoding='utf-8'), tmp)) + '\n')
But since the encoding
parameter for str.encode
has a default value of 'utf-8'
, you can simply make map
use the defaults of str.encode
by passing str.encode
to map
directly: 但是,由于
encoding
的参数str.encode
具有的默认值'utf-8'
,你可以简单地map
使用的默认str.encode
通过传递str.encode
到map
直接:
file.write(' '.join(map(str.encode, tmp)) + '\n')
But since what you really want to do is to convert the entire string you're going to pass to file.write
as bytes, including both ' '
and '\\n'
, which are strings rather than bytes, you should encode the entire string after the joining of the substrings and the concatenation with '\\n'
: 但是,由于您真正想做的是将要传递给
file.write
的整个字符串转换为字节,包括' '
和'\\n'
(均为字符串而不是字节),因此您应该对整个字符串进行编码在子串的连接和'\\n'
的连接之后:
file.write((' '.join(tmp) + '\n').encode())
And since your tmp
is not a list of strings, but rather a list of numpy.float32
objects, you should map them to strings first before joining: 并且由于您的
tmp
不是字符串列表,而是numpy.float32
对象的列表, numpy.float32
在连接之前,应首先将它们映射到字符串:
file.write((' '.join(map(str, tmp)) + '\n').encode())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.