python - 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))
解决方案
该replace()
方法在用于bytes
对象时也需要bytes
对象作为参数。
所以而不是:
word.replace('0', 'O')
写:
word.replace(b'0', b'O')
但是,如果您正在处理文本,我想知道为什么您使用bytes
对象而不是str
对象。直接在字符串上工作更有意义。因此,请确保它word
是 typestr
而不是bytes
thenword.replace('0', 'O')
会按预期工作。为此,您的代码只需要进行两项修改:
- 删除以下语句:
line = line.encode("ascii")
get_type_of_word()
只是使用而c
不是chr(c)
另请注意,这word.replace('0', 'O')
没有任何效果,因为它并没有真正改变单词,而是返回它的(修改后的)副本。因此,您应该将其分配给任何效果,例如word = word.replace('0', 'O')
.
推荐阅读
- azure - 没有运行时 Azure 服务总线传入请求
- java - 在 Java 8 中使用流按 Map 值分组
- angular-dart - 在 AngularDart 中路由到 webdev 服务
- airflow - 气流:第一个操作员完成后如何并行启动操作员
- ios - Branch.io 链接 Facebook 问题
- android - 通过数据绑定在 XML 中切换自定义视图的可见性
- selenium-webdriver - cucumber-jvm 和 selenium WebDriver 的全局环境变量
- python - 保存带有一些额外信息的 DataFrame
- wpf - MVVM中控件可见性的DesignTime修改
- c# - 从资源子文件夹中获取文件名