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

时间:2019-07-18 19:19:28

标签: python python-3.x typeerror

所以我正在尝试替换字符串中的一些字符,但是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))

1 个答案:

答案 0 :(得分:1)

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

所以代替:

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

写:

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

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

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

还请注意,word.replace('0', 'O')无效,因为它不会真正更改单词,但会返回该单词的(修改的)副本。因此,您应该将其分配为有效,例如word = word.replace('0', 'O')