2017-05-22 9 views
1

こんにちはのpython 3.6を使用して私のコードイムに問題があると私は(ファイル.TXTを開き、私のurllib.request.urlopenへの送信のためのテキストを読む)しかし、私は、既知のエラーを持っています私のtxtファイルは、スペースと\を持っているためそれはnが、Pythonで、ここで完全に 2.7仕事は私のコードです:のpython 3.xおよびurllibは

import urllib.request 
import urllib.parse 

def readtext(): 
     quotes = open("C:/Users/sdand/Documents/Python/udacity/curse.txt") 
     contents_of_files = quotes.read() 
     print(contents_of_files) 
     quotes.close() 
     check_profanity(contents_of_files) 

def check_profanity(text): 
     req = urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text) 
     output = req.read() 
     req.close() 


readtext() 

、これが私のエラーです:

Traceback (most recent call last): 
    File "C:/Users/sdand/Documents/Python/udacity/profanity.py", line 17, in <module> 
    readtext() 
    File "C:/Users/sdand/Documents/Python/udacity/profanity.py", line 9, in readtext 
    check_profanity(contents_of_files) 
    File "C:/Users/sdand/Documents/Python/udacity/profanity.py", line 12, in check_profanity 
    req = urllib.request.urlopen("http://www.wdylike.appspot.com/?q="+text) 
    File "C:\Program Files\Python36\lib\urllib\request.py", line 223, in urlopen 
    return opener.open(url, data, timeout) 
    File "C:\Program Files\Python36\lib\urllib\request.py", line 532, in open 
    response = meth(req, response) 
    File "C:\Program Files\Python36\lib\urllib\request.py", line 642, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "C:\Program Files\Python36\lib\urllib\request.py", line 570, in error 
    return self._call_chain(*args) 
    File "C:\Program Files\Python36\lib\urllib\request.py", line 504, in _call_chain 
    result = func(*args) 
    File "C:\Program Files\Python36\lib\urllib\request.py", line 650, in http_error_default 
    raise HTTPError(req.full_url, code, msg, hdrs, fp) 
urllib.error.HTTPError: HTTP Error 400: Bad Request 

私はあなたに感謝助けて感謝

+0

これはちょうど私のテキストがcontents_of_filesの中にあるのを見るためです: - ヒューストンくそ、問題があります。 (アポロ13号) - ママはいつも言ったように、人生はチョコレートの箱のようなものです。あなたは何を得るつもりか分からない。 (フォレストガンプ) - あなたは真実を扱うことはできません。 (少数の良い男性) - 私はすべてを信じ、私は何も信じていません。 (暗闇の中でのショット) –

答えて

0

クエリ文字列エスケープ:

def check_profanity(text): 
    req = urllib.request.urlopen("http://www.wdylike.appspot.com/?" + urllib.parse.urlencode([('q', text)])) 
    output = req.read() 
    req.close() 

urllib.request.urlopenを、指定したurlにGET要求を送信します。どうやら、文字列がエンコードされたURLであるかどうかは確認されず、それ自体を実行しようとしません。

URLに空白などの特殊文字を使用することはできません。有効なURLにエンコードする必要があります(space+に置き換えるなど)。

基本的に、ファイルから読み込んだコンテンツは、適切なhttp urlとしてエンコードされていません。これはurllib.parse.urlencodeによって行われます。

urllib.parse.urlencodeは、キーと値のペアを持つタプルのリストをとります。

基本的には、URLで消費する準備ができている

urllib.parse.urlencode([('q', 'value'), ('another', 'value with spaces & other *special* chars')]) 
# equals: 
# q=value&another=value+with+spaces+%26+other+%2Aspecial%2A+chars 

+1

それはあなたに感謝します!、この部分は何ですか?urllib.parse.urlencode([( 'q'、text)]))を教えてください。 –

関連する問題