我试图运行这个亵渎性检查器,但我得到一个“TypeError:需要一个类似字节的对象,而不是'str'”。我该如何解决这个问题?
这是代码;
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()
这是我尝试运行程序时抛出的错误。
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'
>>>
答案 0 :(得分:2)
这是因为connection.read()
返回字节,只需使用enconding对其进行解码,很可能是utf-8
例如,要执行以下操作:
connection.read().decode('utf-8')