2013-04-20 16 views
3

我试图使用http://grantcox.com.au/2012/01/decoding-b4u-binary-file-format/ Python代码将.b4u文件导出为HTML格式,但由于某些原因在程序点后:Python - 读取.b4u文件 - 错误序列项目0:期望的str实例,找到的字节

# find the initial caret position - this changes between files for some reason - search for the "Cards" string 
for i in range(3): 
    addr = 104 + i*4 
    if ''.join(self.parser.read('sssss', addr)) == 'Cards': 
     caret = addr + 32 
     break 
    if caret is None: 
     return 

我得到以下错误:

if ''.join(self.parser.read('sssss', addr)) == 'Cards': 
TypeError: sequence item 0: expected str instance, bytes found 

我使用的Python版本是:Python的3.3.1(V3.3.1:d9893d13c628,2013年4月6日,20时25分12秒)。

任何想法如何解决这个问题?

+0

你是否解决了你的问题? – 2015-05-10 15:30:13

回答

0

我得到它在Python 2.7.4下工作我的Python 3.3.2给了我同样的错误。如果我发现如何将这段代码移植到Python 3.xx中,我会回复你。与Python 3中的字符串默认使用的unicode有关。 下面是我想出的一个解决方案:

def read(self, fmt, offset): 
    if self.filedata is None: 
     return None 
    read = struct.unpack_from('<' + fmt, self.filedata, offset) 
    xread = [] 
    for each in range(0,len(read)): 
     try: 
       xread.append(read[each].decode()) 
     except: 
       xread.append(read[each]) 
    read = xread 
    if len(read) == 1: 
     return read[0] 
return read 

def string(self, offset): 
    if self.filedata is None: 
     return None 
    s = u'' 
    if offset > 0: 
     length = self.read('H', offset) 
     for i in range(length): 
      raw = self.read('H', offset + i*2 +2) 
      char = raw^0x7E 
      s = s + chr(char) 
    return s 

def plain_fixed_string(self, offset): 
    if self.filedata is None: 
     return None 
    plain_bytes = struct.unpack_from('<ssssssssssssssssssssssss', self.filedata, offset) 
    xplain_bytes = [] 
    for each in range(0,len(plain_bytes)): 
      try: 
        xplain_bytes.append(plain_bytes[each].decode()) 
      except: 
        xplain_bytes.append(plain_bytes[each]) 
    plain_bytes = xplain_bytes 
    plain_string = ''.join(plain_bytes).strip('\0x0') 
    return plain_string 

您可以使用这些方法而不是原作者提供的方法。 请注意,如果您在任何地方看到它,还应该将unicode()更改为str()和unichr()以chr()。还要记住,print是一个函数,不能使用括号()。

+0

解决了我的解决方案吗? – 2013-08-04 22:25:57

相关问题