gpt4 book ai didi

python - 使用 urllib.request 时出现 HTTP 错误

转载 作者:行者123 更新时间:2023-12-01 03:05:56 25 4
gpt4 key购买 nike

我正在尝试进行脏话检查测试。到目前为止我编写的代码是

import urllib.request  

def read_text ():
file = open (r"C:\Users\Kashif\Downloads\abc.txt")
file_print = file.read ()
print (file_print)
file.close ()
check_profanity (file_print)

def check_profanity (file_print):
connection = urllib.request.urlopen ("http://www.purgomalum.com/service/containsprofanity?text="+file_print)
output = connection.read ()
print ("The Output is "+output)
connection.close ()
read_text ()

但我收到以下错误

urllib.error.HTTPError: HTTP Error 400: Bad Request

我不知道我出了什么问题。

我使用的是Python 3.6.1

最佳答案

您收到的 HTTP 错误通常表明您向服务器请求数据的方式存在问题。根据HTTP Spec :

400 Bad Request

The request could not be understood by the server due to malformedsyntax. The client SHOULD NOT repeat the request without modifications

具体而言,在您的示例中,问题似乎在于您在 URL 中发送的数据缺乏 URL 编码。您应该尝试使用 urllib.parse 中的 quote_plus 方法模块使您的请求可接受:

from urllib.parse import quote_plus

...

encoded_file_print = quote_plus(file_print)
url = "http://www.purgomalum.com/service/containsprofanity?text=" + encoded_file_print
connection = urllib.request.urlopen(url)

如果这不起作用,则问题可能出在您的文件内容上。您可以先尝试一个简单的示例,以验证您的脚本是否有效,然后尝试使用该文件的内容。

除了上述问题之外,您的代码还存在一些其他问题:

  1. 方法和括号之间不需要空格:file.close ()def read_text (): 等。

  2. 读取内容后对其进行解码,将字节转换为字符串:output = connection.read().decode('utf-8')

  3. 调用方法的方式创建了循环依赖。 read_text 调用 check_profanity,最终调用 read_text 调用 check_profanity,等等。删除额外的方法调用,只需使用 return 返回方法的输出:

    content = read_text()
    has_profanity = check_profanity(content)
    print("has profanity? %s" % has_profanity)

关于python - 使用 urllib.request 时出现 HTTP 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43427004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com