首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >"TypeError:需要一个类似字节的对象,而不是'str'“。我该如何解决这个问题呢?

"TypeError:需要一个类似字节的对象,而不是'str'“。我该如何解决这个问题呢?
EN

Stack Overflow用户
提问于 2018-01-16 16:56:14
回答 1查看 13.2K关注 0票数 3

我试图运行这个亵渎检查器,但是我得到了一个"TypeError:需要一个类似字节的对象,而不是'str'“。我该如何解决这个问题呢?

以下是代码;

代码语言:javascript
复制
import urllib.request
import urllib.parse

def read_text():
    quotes = open("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)
    output = connection.read()
    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()

这是当我尝试运行程序时抛出的错误。

代码语言:javascript
复制
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: C:\Users\User\AppData\Local\Programs\Python\Python36-32\check_profanity.py 
Houston, we have a problem
(Apollo 13)

Mama always said, life is like a box of chocolates.
You never know what you are going to get.
(Forrest Gump)

You can't handle the truth.
(A Few Good Men)

I beleieve everything and I believe nothing.
(A Shit in the Dark)
b'true'
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\check_profanity.py", line 25, in <module>
    read_text()
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\check_profanity.py", line 9, in read_text
    check_profanity(contents_of_file)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\check_profanity.py", line 18, in check_profanity
    if "true" in output:
TypeError: a bytes-like object is required, not 'str'
>>> 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-16 18:04:38

这是因为connection.read()返回字节,所以只需使用编码进行解码,很可能是utf-8

例如,执行以下操作:

代码语言:javascript
复制
connection.read().decode('utf-8')
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48277354

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档