Python: 将二进制字符串转换为文本文件

Python: Converting a Binary String to a Text File

我已经编写了一个代码,可以将文本文件 a.txt 中的文本转换为二进制字符串 Binary,现在我想做相反的事情,

换句话说,我想将二进制字符串 Binary 转换成文本文件 b.txt which has same text as the text file a.txt,

我该怎么做?

代码如下,请根据代码给出解决方案:

content = open('a.txt', 'r').read()
test_str = content
# using join() + ord() + format()  ... Converting String to binary 
Binary = ''.join(format(ord(i), 'b') for i in test_str)   

# printing original string  
print("The original string is : " + str(test_str)) 
# printing result  
print("The string after Binary conversion : \n" + str(Binary))

编辑:

  1. 我试图将二进制字符串 Binary 转换为文本字符串,但我得到了未知字符,它不在文本文件 a.txt.

  2. 如果我在''.join(format(ord(i), 'b') for i in test_str)中提供space那么我也无法在字符串中得到一个句子,我得到错误,字符串得到spaces,我不需要,我需要一个完整的字符串,字符串 Binary 中没有 space。我尝试了以下代码进行重新转换:

    n = int(二进制, 2)

    print(n.to_bytes((n.bit_length() + 7) // 8,'big').decode())

与复制相关的免责声明Post:

这不是重复你指的 post 是不同的,post 询问 "in other words, if i have binary number, i want to convert it to a text file." 这是完全不同的,

您需要一些识别字符边界的方法。如果您将其限制为设定的位长度——比如仅 8 位,您可以填充二进制文件,然后您就会知道字符大小。如果你不想这样做,你需要一些其他的方式。

这是一个不关心输入的方法——它处理 spaces、表情符号等。它通过用 space 分隔二进制文件中的字符来做到这一点:

test_str = "Dies ist eine binäre Übersetzung. "

Binary = ' '.join(format(ord(i), 'b') for i in test_str)   

print("original:")
print(test_str)

print("\nThe string after Binary conversion : \n" + Binary)

text = "".join(chr(int(s, 2)) for s in  Binary.split())
print(f'\nString after conversion back to text:\n{text}')

这会打印:

original:
Dies ist eine binäre Übersetzung.

The string after Binary conversion :
1000100 1101001 1100101 1110011 100000 1101001 1110011 1110100 100000 1100101 1101001 1101110 1100101 100000 1100010 1101001 1101110 11100100 1110010 1100101 100000 11011100 1100010 1100101 1110010 1110011 1100101 1110100 1111010 1110101 1101110 1100111 101110 100000 11111010000111011

String after conversion back to text:
Dies ist eine binäre Übersetzung.

注意表情符号的最后一个字符以及二进制文件的长度。那可能是熊表情符号或几个 ascii 字符。没有分隔符,现在有办法知道了。