首页 > 解决方案 > TypeError:需要一个类似字节的对象,而不是'str',但类型是'bytes'

问题描述

所以我试图替换字符串中的一些字符,但 python 不能正确识别它的类型。任何想法为什么会这样?

...
print(type(word))
word.replace('0', 'O')
...
<class 'bytes'> 

已打印但我得到:

TypeError:需要一个类似字节的对象,而不是“str”


因此,我正在对账单中已识别的文本进行一些文本更正。我在 self.text 变量中有一个可识别的文本,它有一个<str class>.

 def text_correction(self):
        '''
            Post processing, replace some characters.
        '''
        self.total = ""
        self.date = ""
        print(type(self.text))   #return <class 'str'> 

        lines = self.text.split('\n')
        new_string = ""

        for line in lines:

            line = line.encode("ascii")
            new_line = ""

            words = line.split()

            for word in words:

                type_of_word = self.get_type_of_word(word)
                print(type(word)) #return <class 'bytes'>
                if type_of_word == 0:
                    word.replace('0', 'O')
                    word.replace('l', 'I')
             ...

get_type_of_word 函数只是检查字符是上/下还是数字:

 def get_type_of_word(self, word):
        '''
            Define type of word.
        '''
        type_of_word = []
        count =0
        type_of_word.append(sum(1 for c in word if chr(c).isupper()))
        type_of_word.append(sum(1 for c in word if chr(c).islower()))
        type_of_word.append(sum(1 for c in word if chr(c).isdigit()))
        type_of_word.append(len(word) - sum(type_of_word))

        if type_of_word[0] == type_of_word[2] and type_of_word[0] != 0:
            return 2
        else:
            return type_of_word.index(max(type_of_word))

标签: pythonpython-3.xtypeerror

解决方案


replace()方法在用于bytes对象时也需要bytes对象作为参数。

所以而不是:

word.replace('0', 'O')

写:

word.replace(b'0', b'O')

但是,如果您正在处理文本,我想知道为什么您使用bytes对象而不是str对象。直接在字符串上工作更有意义。因此,请确保它word是 typestr而不是bytesthenword.replace('0', 'O')会按预期工作。为此,您的代码只需要进行两项修改:

  • 删除以下语句:line = line.encode("ascii")
  • get_type_of_word()只是使用而c不是chr(c)

另请注意,这word.replace('0', 'O')没有任何效果,因为它并没有真正改变单词,而是返回它的(修改后的)副本。因此,您应该将其分配给任何效果,例如word = word.replace('0', 'O').


推荐阅读