Reputation: 63
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'
Upvotes: 1
Views: 5506
Reputation: 106648
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.
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:
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:
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((' '.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:
file.write((' '.join(map(str, tmp)) + '\n').encode())
Upvotes: 1
Reputation: 71580
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
Upvotes: 1