我在理解python2的foo.decode("hex")
命令时遇到了一些问题。通过求解this problem,我在python2.7.12中获得了以下结果(其中_阿尔法.txt是一个4 MB的字典)。你知道吗
words = open("words_alpha.txt").read().split('\n')
def xor(x, y):
if len(x) == len(y):
return "".join([chr(ord(x[i]) ^ ord(y[i])) for i in range(len(x))])
def single_char_xors(msg):
for i in range(128):
yield [chr(i), xor(msg, chr(i)*len(msg))]
def real_word_count(S): # Assumes there is at least one three-letter word in the string S.
count = 0
for word in filter(lambda s: s.isalpha() and len(s) >= 3, S.split(' ')):
if word.lower() in words:
count += 1
return count
hexes = open("4.txt").read().split('\n')
hexes = [x.decode("hex") for x in hexes]
answer = []
maxwc = 0
for x in hexes:
for y in single_char_xors(x):
if real_word_count(y[1]) > maxwc:
answer = [x] + y
maxwc = real_word_count(y[1])
print answer[0] + " xor " + answer[1] + " is " + answer[2]
在python3中,foo.decode("hex")
被弃用。但是用hexes = [binascii.unhexlify(x).decode() for x in hexes]
替换hexes = [x.decode("hex") for x in hexes]
会
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 3: invalid continuation byte
而hexes = [binascii.unhexlify(x).decode("utf-8", "ignore") for x in hexes]
(或"replace"
、"backslashreplace"
等)工作正常。那么foo.decode("hex")
在做什么binascii.unhexlify(foo).decode()
在默认情况下不做的事情呢?你知道吗
我相信问题出在
.decode("utf-8", "ignore")
——使用"ignore"
参数,您实际上忽略了在第一种情况下引发UnicodeDecodeError
异常的问题。你知道吗binascii.hexlify
和codecs.decode
之间的区别:比纳西.赫克斯利夫
二进制数据的十六进制表示法。你知道吗
返回值是bytes对象。你知道吗
类型:内置函数或方法
编解码器.decode
.decode(obj,encoding='utf-8',errors='strict')
使用注册的编解码器解码obj编码。错误可以给出设置所需的错误处理方案。默认的错误处理程序是“strict”,这意味着解码错误会引发ValueError(或更特定于编解码器的子类,如UnicodeDecodeError)。有关编解码器错误处理的详细信息,请参阅编解码器基类。你知道吗
类型:内置函数或方法
相关问题 更多 >
编程相关推荐