你好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
控制台输出:
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
答案 0 :(得分:21)
修复对我来说很简单
使用
--dry-run
而不是
f = open('bytes.bin', 'w')
在python 3中f = open('bytes.bin', 'wb')
是你需要的,而不是'w'
。
答案 1 :(得分: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)
并且在另一个功能中有几行需要类似的处理。
有关详细信息,请参阅Porting to Python 3和Bytes, Strings and Unicode部分。