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')
在函数调用的时候第二个参数前面需要加上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中3+版本运行2+版本程序出现TypeError: a bytes-like object is required, not 'str'之读取PDF中的图片
- python3中,socket使用send函数时出现的错误:TypeError: a bytes-like object is required, not 'str'
- python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file
- python write()参数错误,导致报错TypeError: a bytes-like object is required, not 'str'
- python3.5 模拟UDP客户端发送数据报文,报错:TypeError: a bytes-like object is required, not 'str'
- python中Base64编码和解码:TypeError: a bytes-like object is required, not 'str'
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- Python 3.x: TypeError: a bytes-like object is required, not 'str'
- python socket send 函数 报错:TypeError: a bytes-like object is required, not 'str'
- Python 3.x Error:TypeError: a bytes-like object is required, not 'str'
- TypeError: a bytes-like object is required, not 'str'
- 解决python3的pickle.load错误:a bytes-like object is required, not 'str'
- Python中“a bytes-like object is required, not 'str'”的问题
- linux下运行python3出现TypeError: a bytes-like object is required, not 'str'
- python3 TypeError: a bytes-like object is required, not 'str'
- python3 TypeError: a bytes-like object is required, not 'str'
- Error:a bytes-like object is required not str
- TypeError: a bytes-like object is required, not 'str'
- 【Python】TypeError: a bytes-like object is required, not 'str'解决
- TypeError:a bytes-like object is requeired ,not 'int'(使用python3编写出现的错误)