Dan*_*ngo 13 python string unicode bytearray python-3.x
你好Py2中的这两个功能工作正常,但它不适用于Py3
def encoding(text, codes):
binary = ''
f = open('bytes.bin', 'wb')
for c in text:
binary += codes[c]
f.write('%s' % binary)
print('Text in binary:', binary)
f.close()
return len(binary)
def decoding(codes, large):
f = file('bytes.bin', 'rb')
bits = f.read(large)
tmp = ''
decode_text = ''
for bit in bits:
tmp += bit
if tmp in fordecodes:
decode_text += fordecodes[tmp]
tmp = ''
f.close()
return decode_text
Run Code Online (Sandbox Code Playgroud)
控制台输出:
Traceback (most recent call last):
File "Practica2.py", line 83, in <module>
large = encoding(text, codes)
File "Practica2.py", line 56, in encoding
f.write('%s' % binary)
TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)
Jim*_*mmy 21
修复对我来说很简单
使用
f = open('bytes.bin', 'w')
Run Code Online (Sandbox Code Playgroud)
代替
f = open('bytes.bin', 'wb')
Run Code Online (Sandbox Code Playgroud)
在python 3 'w'中你需要的不是'wb'.
ekh*_*oro 13
在Python 2中,裸文字字符串(例如'string')是字节,而在Python 3中它们是unicode.这意味着如果您希望在Python 3中将文字字符串视为字节,则必须明确标记它们.
因此,例如,encoding函数的前几行应如下所示:
binary = b''
f = open('bytes.bin', 'wb')
for c in text:
binary += codes[c]
f.write(b'%s' % binary)
Run Code Online (Sandbox Code Playgroud)
并且在另一个功能中有几行需要类似的处理.
有关更多详细信息,请参阅移植到Python 3,以及字节,字符串和Unicode部分.