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

在做一个统计文本中的一个单词出现了多少次的练习中遇到的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')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值