Python 如何使用字符编码在文件中存储随机字节?
我正在尝试在Python3(使用Windows7)上运行其他人的Python2程序。其目的是生成大的阶乘,然后将其用作随机数流。程序将十进制阶乘转换为0到255之间的字节值,并将Python 如何使用字符编码在文件中存储随机字节?,python,random,encoding,Python,Random,Encoding,我正在尝试在Python3(使用Windows7)上运行其他人的Python2程序。其目的是生成大的阶乘,然后将其用作随机数流。程序将十进制阶乘转换为0到255之间的字节值,并将chr(字节值)写入文件。它通过以8位小数的部分遍历阶乘来计算每个字节。然而,编码从Python2改为3(我不确定它到底起什么作用或为什么起作用),并且chr()命令对128到159之间的任何值都不起作用(但值160到255起作用)-程序会引发“unicodeincoder错误:'charmap'编解码器无法编码字符”(
chr(字节值)
写入文件。它通过以8位小数的部分遍历阶乘来计算每个字节。然而,编码从Python2改为3(我不确定它到底起什么作用或为什么起作用),并且chr()
命令对128到159之间的任何值都不起作用(但值160到255起作用)-程序会引发“unicodeincoder错误:'charmap'编解码器无法编码字符”(字符点)'在位置0:字符映射到
“
我已尝试使用“open(filename,“w”,encoding=“utf-8”)
”更改文件编码,这成功地写入了所有字节。然而,当我测试文件的随机性属性时,它们明显比作者得到的结果差
在不影响数据随机性的情况下,我应该更改哪些内容来存储字符字节?
测试程序称为“ent”。在命令提示符下,它将一个文件作为参数,然后输出一些随机性统计数据。欲了解更多信息,请访问其网站
- 来自的文件的我的ent结果!500000,使用
:打开(文件名,“w”,encoding=“utf-8”)
- 作者对来自的文件的ent结果!50万:
Entropy = 7.999373 bits per byte. Optimum compression would reduce the size of this 313417 byte file by 0 percent. Chi square distribution for 31347 samples is 272.63, and randomly would exceed this value 25.00 percent of the times. Arithmetic mean value of data bytes is 127.6336 (127.5 = random). Monte Carlo value for Pi is 3.149475458 (error 0.25 percent). Serial correlation coefficient is -0.001209 (totally uncorrelated = 0.0).
- 可以对字符(128到159)进行编码吗
- 我们能把所有的数据以二进制形式写入一个文件吗
- 这里有一个示例(在Python 3中):
其中我们测试了两种理论:
看起来timakro已经找到了答案(谢谢):
“要写入二进制文件,应以二进制模式打开(文件名为“wb”),并向其写入类似字节的对象。例如,要写入值为123的字节:file.write(字节([123])。”-timakro
当我将“
字节([byte value from 0-255])
”写入文件时,它会获得ent程序预期的随机性分数。因此,我将Python2的chr()
更改为bytes()
,以便程序在Python3中存储字节。无需字符编码。要编写二进制文件,应以二进制模式打开它。open(filename,“wb”)
并向其写入类似字节的对象。例如,写一个值为123的字节:file.write(bytes([123]))
。在Python2世界中,“一个字节”和“一个字符”是可互换的;在Python3/Unicode世界中,世界上有数千个字符,因此每个字符需要多个字节来存储(而且“字符”的概念也很模糊)。现在中间还有另一层:文本是一个Unicode代码点序列“ABé”->可以选择编码方式如何将它们序列化到字节值->不透明的序列化数据字节块。“A”的字节值取决于您选择的序列化程序(utf8),编码将模式添加到数据中。此方法相当于我提到的命令—“open(filename,“w”,encoding=“utf-8”)—即使在“wb”中也是如此。问题在于,这改变了由ent程序测量的数据的随机性。
Entropy = 7.999373 bits per byte.
Optimum compression would reduce the size of this 313417 byte file by 0 percent.
Chi square distribution for 31347 samples is 272.63, and randomly would
exceed this value 25.00 percent of the times.
Arithmetic mean value of data bytes is 127.6336 (127.5 = random).
Monte Carlo value for Pi is 3.149475458 (error 0.25 percent).
Serial correlation coefficient is -0.001209 (totally uncorrelated = 0.0).
# check if the characters are matching Unicode
l1 = [chr(i) for i in range(128, 160)]
print("{}\n".format(l1))
s1 = " ".join(l1)
# display these characters for visual comparison
# before writing them to file
print("INITIAL:")
print(s1)
pf = open("somefile", "wb")
pf.write(s1.encode("utf-8"))
pf.close()
po = open("somefile", "rb")
out = po.read()
po.close()
s2 = out.decode('utf-8')
# display these characters for visual comparison
# after writing them to file and reading them from it
print("AFTER:")
print(s2)