首页 > 解决方案 > python3 TypeError:'bytes'对象不可调用

问题描述

我的代码:

 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'

标签: pythonpython-3.x

解决方案


做:

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

代替:

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

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


推荐阅读