我目前正在Python中为学校项目编写一个ascii-binary / binary-ascii转换器,我有一个从ascii(String text)转换为二进制文件的问题。我们的想法是在代码底部的test()中打印结果。
在WingIDE中运行代码时,会发生错误: 在以
开头的行上bnary = bnary + binary[chnk]
KeyError:"挪威以30:28击败波兰并破坏Bielecki的生日派对。"
我在这里尝试做的是转换存储在" text.txt"中的文本字符串。到一个整数字符串,然后打印这个二进制字符串。
非常感谢任何帮助。我试着查看其他ascii-binary反之亦然转换相关问题,但似乎没有一个对我有用。
我的代码:
def code():
binary = {}
ascii = {}
# Generate ascii code
for i in range(0,128) :
ascii[format(i,'08b')] = chr(i)
# Reverse the ascii code, this will be binary
for k, v in ascii.iteritems():
binary[v] = binary.get(v, [])
binary[v].append(k)
return ascii
def encode(text,binary):
'''
Encode some text using text from a source
'''
bnary = ""
fi = open(text, mode='rb')
while True:
chnk = fi.read()
if chnk == '':
break
if chnk != '\n':
binry = ""
bnary = bnary + binary[chnk]
return bnary
def decode(sourcecode,n, ascii):
'''
Decode a sourcecode using chunks of size n
'''
sentence = ""
f = open(sourcecode, mode='rb') # Open a file with filename <sourcecode>
while True:
chunk = f.read(n) # Read n characters at time from an open file
if chunk == '': # This is one way to check for the End Of File in Python
break
if chunk != '\n':
setence = "" # The ascii sentence generated
# create a sentence
sentence = sentence + ascii[chunk]
return sentence
def test():
'''
A placeholder for some test cases.
It is recommended that you use some existing framework, like unittest,
but for a temporary testing in a development version can be done
directly in the module.
'''
print encode('text.txt', code())
print decode('sourcecode.txt', 8, code())
test()
答案 0 :(得分:4)
如果您想要解码和编码,请使用此解决方案
将ascii编码到bin
def toBinary(string):
return "".join([format(ord(char),'#010b')[2:] for char in string])
将bin编码为ascii
def toString(binaryString):
return "".join([chr(int(binaryString[i:i+8],2)) for i in range(0,len(binaryString),8)])
答案 1 :(得分:1)
fi.read()第一次和“下次”返回整个文档。所以你应该做
text = fi.read()
for char in text:
do_stuff()
<强> EDIT1 强>
您只能阅读一次文件。因此,你必须逐个获取你的字符。 file.read返回包含整个文档的字符串。
您可以遍历字符串以逐个获取字符。
主要错误是您的binary
是{"a":['010001110'], "b":...}
并且您尝试使用密钥"azerty"
进行访问,您应该通过char来执行char:
string = "azer"
result = []
for c in string:
result += binary[c]
>>> result = [['11001'],[1001101'],...]
答案 2 :(得分:1)
# Lets say your filename is stored in fname
def binary(n):
return '{0:08b}'.format(n)
with open(fname) as f:
content = f.readlines()
for i in content:
print(binary(ord(i)), end='')
print('')
这将为您提供文件中每个字符的整数值(来自ascii),逐行