如何使用python3检查亵渎性

时间:2015-06-25 18:02:54

标签: python

请帮我用代码解决问题:

import urllib.request
import urllib.parse

def read_text():

    quotes= open("C:\\Users\\no1\\Desktop\\movie_quotes.txt")
    content_of_file=quotes.read()
    quotes.close()
    check_profanity(content_of_file)

def check_profanity(text_to_check):
    a=urllib.parse.urlencode(text_to_check)
    a=a.encode('utf-8')
    connection=urllib.request.urlopen("http://www.wdyl.com/profanity?q=",a)
    output=connection.read()
    print(output)
    connection.close()

read_text()

我想检查亵渎,但代码没有用。

以下是来自python的反馈:

Traceback (most recent call last):
  File "C:\Python34\lib\urllib\parse.py", line 760, in urlencode
    raise TypeError
TypeError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\no1\Desktop\check profanity.py", line 19, in <module>
    read_text()
  File "C:\Users\no1\Desktop\check profanity.py", line 9, in read_text
    check_profanity(content_of_file)
  File "C:\Users\no1\Desktop\check profanity.py", line 12, in check_profanity
    a=urllib.parse.urlencode(text_to_check)
  File "C:\Python34\lib\urllib\parse.py", line 768, in urlencode
    "or mapping object").with_traceback(tb)
  File "C:\Python34\lib\urllib\parse.py", line 760, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object

2 个答案:

答案 0 :(得分:2)

www.wdyl.com不再工作了。

您可以使用您喜欢的内容: http://www.wdylike.appspot.com/?q=foo

这是我的工作代码:

import urllib.request
import urllib.parse

def read_text():
    quotes = open("movie_quotes.txt")  # Returns a `file` object
    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
    print(address)
    connection = urllib.request.urlopen(address)
    output = connection.read()
    print(output)
    connection.close()

read_text()

答案 1 :(得分:0)

这是另一种类似的方式:

from django.utils.encoding import smart_str
import urllib

def check_profanity(to_check):
    try:
        connection = urllib.urlopen('http://www.wdyl.com/profanity?q='\ 
                    + smart_str(to_check))
        output = connection.read()
        connection.close()
        if 'true' in output:  
            return True
        else:
            return False  
    except:
        print "An error occurred!"
        return
相关问题