繁体   English   中英

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

[英]TypeError: a bytes-like object is required, not 'str' but type is 'bytes'

所以我试图替换字符串中的一些字符,但是python无法正确识别其类型。 知道为什么吗?

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

打印,但我得到:

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


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

 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函数只是检查char是高/低还是数字:

 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))

当在bytes对象上使用replace()方法时,方法也需要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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM