You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行脏话检查器时遇TypeError: a bytes-like object is required, not 'str'如何修复?

解决TypeError: a bytes-like object is required, not 'str'问题

嘿,我看到你遇到的这个错误了,问题出在Python3对字节和字符串的严格区分上,咱们一步步来修复它:

问题根源

你代码里的output = connection.read()返回的是bytes类型的数据(从输出里的b'true'也能看出来,前缀b就代表这是bytes对象),但你后面用字符串"true"去判断是否包含在其中,Python3不允许直接在bytes和str之间做这样的成员判断,所以触发了这个TypeError。

修复步骤

1. 把bytes转成字符串

在获取网络响应后,调用decode()方法把bytes解码成UTF-8格式的字符串,这样就能和普通字符串做比较了:

output = connection.read().decode('utf-8')

2. 修复文件路径的转义问题

另外,你的文件路径"C:\Check Profanity\movie_quotes.txt"里的反斜杠会被Python当成转义字符,可能导致程序找不到文件,建议改成原始字符串或者用双反斜杠:

# 原始字符串写法(推荐)
quotes = open(r"C:\Check Profanity\movie_quotes.txt")
# 或者双反斜杠写法
quotes = open("C:\\Check Profanity\\movie_quotes.txt")

修改后的完整代码

import urllib.request
import urllib.parse

def read_text():
    # 修复路径转义问题
    quotes = open(r"C:\Check Profanity\movie_quotes.txt")
    contents_of_file = quotes.read()
    print(contents_of_file)
    quotes.close()
    check_profanity(contents_of_file)

def check_profanity(text_to_check):
    encoded_text = urllib.parse.quote(text_to_check, 'utf-8')
    address = "http://www.wdylike.appspot.com/?q="+encoded_text
    connection = urllib.request.urlopen(address)
    # 把bytes解码成字符串
    output = connection.read().decode('utf-8')
    print(output)
    connection.close()
    if "true" in output:
        print("Profanity Alert!")
    elif "false" in output:
        print("This document has no curse words!")
    else:
        print("Could not scan the document properly.")

read_text()

额外优化建议

其实你可以用with语句来处理文件,这样不用手动调用close(),代码更简洁安全(with块结束时会自动关闭文件,避免资源泄漏):

def read_text():
    with open(r"C:\Check Profanity\movie_quotes.txt") as quotes:
        contents_of_file = quotes.read()
        print(contents_of_file)
        check_profanity(contents_of_file)

内容的提问来源于stack exchange,提问作者Nelson M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:26:18