您的位置:首页 > 编程语言 > Python开发

Python学习中出现TpyeErrora bytes-like object is required, not 'str'

2018-05-16 09:27 871 查看
在做一个统计文本中的一个单词出现了多少次的练习中遇到的a bytes-like object is required, not 'str'类型错误。

在函数调用的时候第二个参数前面需要加上b

然后最后需要需要用到第二个参数的str类型需要类型转换

str和bytes的互相转换:

# str to bytes
str.encode(s)

# bytes to str
bytes.decode(b)

源代码:

def count_word_number(filename, word):
"""计算文本中一个单词出现了多少次"""
try:
with open(filename, 'rb') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
# msg = "Sorry, the file " + filename + " does not exist."
# print(msg)
pass
else:
# 计算文件中这个单词出现了多少次
num = contents.lower().count(word)
print("Word: '" + bytes.decode(word) + "' appears: " + str(num))

count_word_number('alice.txt', b'the')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 类型错误
相关文章推荐