duckduckgo 모듈이 파이썬 3.4.4에서 작동하지 않습니다.

포도주

안녕하세요 저는 여기 에서 다음 모듈을 얻었습니다.

import urllib
import urllib2
import json as j
import sys

__version__ = 0.242


def query(query, useragent='python-duckduckgo '+str(__version__), safesearch=True, html=False, meanings=True, **kwargs):
    """
    Query DuckDuckGo, returning a Results object.
    Here's a query that's unlikely to change:
    >>> result = query('1 + 1')
    >>> result.type
    'nothing'
    >>> result.answer.text
    '1 + 1 = 2'
    >>> result.answer.type
    'calc'
    Keword arguments:
    useragent: UserAgent to use while querying. Default: "python-duckduckgo %d" (str)
    safesearch: True for on, False for off. Default: True (bool)
    html: True to allow HTML in output. Default: False (bool)
    meanings: True to include disambiguations in results (bool)
    Any other keyword arguments are passed directly to DuckDuckGo as URL params.
    """ % __version__

    safesearch = '1' if safesearch else '-1'
    html = '0' if html else '1'
    meanings = '0' if meanings else '1'
    params = {
        'q': query,
        'o': 'json',
        'kp': safesearch,
        'no_redirect': '1',
        'no_html': html,
        'd': meanings,
        }
    params.update(kwargs)
    encparams = urllib.urlencode(params)
    url = 'http://api.duckduckgo.com/?' + encparams

    request = urllib2.Request(url, headers={'User-Agent': useragent})
    response = urllib2.urlopen(request)
    json = j.loads(response.read())
    response.close()

    return Results(json)


class Results(object):

    def __init__(self, json):
        self.type = {'A': 'answer', 'D': 'disambiguation',
                     'C': 'category', 'N': 'name',
                     'E': 'exclusive', '': 'nothing'}.get(json.get('Type',''), '')

        self.json = json
        self.api_version = None # compat

        self.heading = json.get('Heading', '')

        self.results = [Result(elem) for elem in json.get('Results',[])]
        self.related = [Result(elem) for elem in
                        json.get('RelatedTopics',[])]

        self.abstract = Abstract(json)
        self.redirect = Redirect(json)
        self.definition = Definition(json)
        self.answer = Answer(json)

        self.image = Image({'Result':json.get('Image','')})


class Abstract(object):

    def __init__(self, json):
        self.html = json.get('Abstract', '')
        self.text = json.get('AbstractText', '')
        self.url = json.get('AbstractURL', '')
        self.source = json.get('AbstractSource')

class Redirect(object):

    def __init__(self, json):
        self.url = json.get('Redirect', '')

class Result(object):

    def __init__(self, json):
        self.topics = json.get('Topics', [])
        if self.topics:
            self.topics = [Result(t) for t in self.topics]
            return
        self.html = json.get('Result')
        self.text = json.get('Text')
        self.url = json.get('FirstURL')

        icon_json = json.get('Icon')
        if icon_json is not None:
            self.icon = Image(icon_json)
        else:
            self.icon = None


class Image(object):

    def __init__(self, json):
        self.url = json.get('Result')
        self.height = json.get('Height', None)
        self.width = json.get('Width', None)


class Answer(object):

    def __init__(self, json):
        self.text = json.get('Answer')
        self.type = json.get('AnswerType', '')

class Definition(object):
    def __init__(self, json):
        self.text = json.get('Definition','')
        self.url = json.get('DefinitionURL')
        self.source = json.get('DefinitionSource')


def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', 'definition'], urls=True, **kwargs):
    '''A helper method to get a single (and hopefully the best) ZCI result.
    priority=list can be used to set the order in which fields will be checked for answers.
    Use web_fallback=True to fall back to grabbing the first web result.
    passed to query. This method will fall back to 'Sorry, no results.' 
    if it cannot find anything.'''

    ddg = query('\\'+q, **kwargs)
    response = ''

    for p in priority:
        ps = p.split('.')
        type = ps[0]
        index = int(ps[1]) if len(ps) > 1 else None

        result = getattr(ddg, type)
        if index is not None: 
            if not hasattr(result, '__getitem__'): raise TypeError('%s field is not indexable' % type)
            result = result[index] if len(result) > index else None
        if not result: continue

        if result.text: response = result.text
        if result.text and hasattr(result,'url') and urls: 
            if result.url: response += ' (%s)' % result.url
        if response: break

    # if there still isn't anything, try to get the first web result
    if not response and web_fallback:
        if ddg.redirect.url:
            response = ddg.redirect.url

    # final fallback
    if not response: 
        response = 'Sorry, no results.'

    return response

def main():
    if len(sys.argv) > 1:
        q = query(' '.join(sys.argv[1:]))
        keys = q.json.keys()
        keys.sort()
        for key in keys:
            sys.stdout.write(key)
            if type(q.json[key]) in [str,unicode,int]: print(':', q.json[key])
            else: 
                sys.stdout.write('\n')
                for i in q.json[key]: print('\t',i)
    else:
        print('Usage: %s [query]' % sys.argv[0])

이 코드는 python 2.7에서 제대로 작동하는 것 같지만 3.4에서는 다음 오류가 발생합니다.

Traceback (most recent call last):
  File "E:\Python34\My programs\Novos\duckduckgo.py", line 2, in <module>
    import urllib2
ImportError: No module named 'urllib2'

2to3을 사용해 보았지만 작동하지 않는 다음 코드를 제공했습니다.

import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import json as j
import sys

__version__ = 0.242


def query(query, useragent='python-duckduckgo '+str(__version__), safesearch=True, html=False, meanings=True, **kwargs):
    """
    Query DuckDuckGo, returning a Results object.
    Here's a query that's unlikely to change:
    >>> result = query('1 + 1')
    >>> result.type
    'nothing'
    >>> result.answer.text
    '1 + 1 = 2'
    >>> result.answer.type
    'calc'
    Keword arguments:
    useragent: UserAgent to use while querying. Default: "python-duckduckgo %d" (str)
    safesearch: True for on, False for off. Default: True (bool)
    html: True to allow HTML in output. Default: False (bool)
    meanings: True to include disambiguations in results (bool)
    Any other keyword arguments are passed directly to DuckDuckGo as URL params.
    """ % __version__

    safesearch = '1' if safesearch else '-1'
    html = '0' if html else '1'
    meanings = '0' if meanings else '1'
    params = {
        'q': query,
        'o': 'json',
        'kp': safesearch,
        'no_redirect': '1',
        'no_html': html,
        'd': meanings,
        }
    params.update(kwargs)
    encparams = urllib.parse.urlencode(params)
    url = 'http://api.duckduckgo.com/?' + encparams

    request = urllib.request.Request(url, headers={'User-Agent': useragent})
    response = urllib.request.urlopen(request)
    json = j.loads(response.read())
    response.close()

    return Results(json)


class Results(object):

    def __init__(self, json):
        self.type = {'A': 'answer', 'D': 'disambiguation',
                     'C': 'category', 'N': 'name',
                     'E': 'exclusive', '': 'nothing'}.get(json.get('Type',''), '')

        self.json = json
        self.api_version = None # compat

        self.heading = json.get('Heading', '')

        self.results = [Result(elem) for elem in json.get('Results',[])]
        self.related = [Result(elem) for elem in
                        json.get('RelatedTopics',[])]

        self.abstract = Abstract(json)
        self.redirect = Redirect(json)
        self.definition = Definition(json)
        self.answer = Answer(json)

        self.image = Image({'Result':json.get('Image','')})


class Abstract(object):

    def __init__(self, json):
        self.html = json.get('Abstract', '')
        self.text = json.get('AbstractText', '')
        self.url = json.get('AbstractURL', '')
        self.source = json.get('AbstractSource')

class Redirect(object):

    def __init__(self, json):
        self.url = json.get('Redirect', '')

class Result(object):

    def __init__(self, json):
        self.topics = json.get('Topics', [])
        if self.topics:
            self.topics = [Result(t) for t in self.topics]
            return
        self.html = json.get('Result')
        self.text = json.get('Text')
        self.url = json.get('FirstURL')

        icon_json = json.get('Icon')
        if icon_json is not None:
            self.icon = Image(icon_json)
        else:
            self.icon = None


class Image(object):

    def __init__(self, json):
        self.url = json.get('Result')
        self.height = json.get('Height', None)
        self.width = json.get('Width', None)


class Answer(object):

    def __init__(self, json):
        self.text = json.get('Answer')
        self.type = json.get('AnswerType', '')

class Definition(object):
    def __init__(self, json):
        self.text = json.get('Definition','')
        self.url = json.get('DefinitionURL')
        self.source = json.get('DefinitionSource')


def get_zci(q, web_fallback=True, priority=['answer', 'abstract', 'related.0', 'definition'], urls=True, **kwargs):
    '''A helper method to get a single (and hopefully the best) ZCI result.
    priority=list can be used to set the order in which fields will be checked for answers.
    Use web_fallback=True to fall back to grabbing the first web result.
    passed to query. This method will fall back to 'Sorry, no results.' 
    if it cannot find anything.'''

    ddg = query('\\'+q, **kwargs)
    response = ''

    for p in priority:
        ps = p.split('.')
        type = ps[0]
        index = int(ps[1]) if len(ps) > 1 else None

        result = getattr(ddg, type)
        if index is not None: 
            if not hasattr(result, '__getitem__'): raise TypeError('%s field is not indexable' % type)
            result = result[index] if len(result) > index else None
        if not result: continue

        if result.text: response = result.text
        if result.text and hasattr(result,'url') and urls: 
            if result.url: response += ' (%s)' % result.url
        if response: break

    # if there still isn't anything, try to get the first web result
    if not response and web_fallback:
        if ddg.redirect.url:
            response = ddg.redirect.url

    # final fallback
    if not response: 
        response = 'Sorry, no results.'

    return response

def main():
    if len(sys.argv) > 1:
        q = query(' '.join(sys.argv[1:]))
        keys = list(q.json.keys())
        keys.sort()
        for key in keys:
            sys.stdout.write(key)
            if type(q.json[key]) in [str,str,int]: print((':', q.json[key]))
            else: 
                sys.stdout.write('\n')
                for i in q.json[key]: print(('\t',i))
    else:
        print(('Usage: %s [query]' % sys.argv[0]))

두 번째 코드 조각에서 쿼리 함수를 실행할 때 다음 오류가 발생했음을 알 수 있습니다.

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    query("foobar")
  File "E:\Python34\duckduckgo.py", line 45, in query
    json = j.loads(response.read())
  File "E:\Python34\lib\json\__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

그래서 아무도 내가 여기서 뭘 잘못했는지 말해 줄 수 있습니까?

미리 감사드립니다!

포도주

글쎄, 나는 그것에 대한 영혼을 발견했습니다. 코드를 python 3으로 변환 한 후 TypeError: the JSON object must be str, not 'bytes'오류 를 해결하려면

json = j.loads(response.read())` 

`와 함께

reader = codecs.getreader("utf-8")   
json = j.loads(reader(response).read())`

import codecs코드 상단에 추가 합니다.

이 수정은 매력처럼 작동합니다!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Rails 4 Bootstrap3 Dropdown이 작동하지만 작동하지 않습니다.

분류에서Dev

파이썬에서 Tkinter 모듈을 사용하고 배경색 모듈이 작동하지 않습니다.

분류에서Dev

.getjson이 MVc4에서 작동하지 않습니다.

분류에서Dev

Bootstrap이 Rails 4에서 작동하지 않습니다.

분류에서Dev

.profile이 xfce4에서 작동하지 않습니다.

분류에서Dev

opencv2 Aruco 라이브러리 모듈이 파이썬에서 작동하지 않습니다.

분류에서Dev

Eclipse RCP 3.x 플러그인이 Eclipse 4.x에서 올바르게 작동하지 않습니다.

분류에서Dev

Simple_form 클래스 form-horizontal with bootstrap 3이 레일 4에서 작동하지 않습니다.

분류에서Dev

Intel Core i3-4 * 그래픽이 Ubuntu 12.04에서 작동하지 않습니다.

분류에서Dev

무선 어댑터 Broadcom [14e4 : 43a3]이 Ubuntu에서 작동하지 않습니다.

분류에서Dev

무선 어댑터 Broadcom [14e4 : 43a3]이 Ubuntu에서 작동하지 않습니다.

분류에서Dev

Sublime Text 3 용 Autoprefixer 모듈이 작동하지 않습니다.

분류에서Dev

$ _GET이 drupal 모듈에서 작동하지 않습니다.

분류에서Dev

shelve 모듈이 "with"문에서 작동하지 않습니다.

분류에서Dev

파이썬에서 정렬이 작동하지 않습니다

분류에서Dev

파이썬에서 모듈 netcdf4를 사용하여 NetCDF3 파일에 쓰기

분류에서Dev

Rails 4-find_by_ *는 레이크 작업에서 작동하지 않습니다.

분류에서Dev

jQuery 자동 완성이 Rails 4에서 작동하지 않습니다.

분류에서Dev

Angular 4 애니메이션이 Edge에서 작동하지 않습니다.

분류에서Dev

( "") 인쇄가 파이썬에서 작동하지 않습니다.

분류에서Dev

지도가 파이썬 3에서 예상대로 작동하지 않습니다.

분류에서Dev

Spring MVC 4 서비스 @tTransactional이 작동하지 않습니다.

분류에서Dev

MVC4에서 페이징이 작동하지 않습니다.

분류에서Dev

파이썬 isfile이 여기서 작동하지 않습니다.

분류에서Dev

Angular 4 Portal / CdkPortal이 새 자식 창에서 작동하지 않습니다.

분류에서Dev

a4j : outputPanel에서 렌더링이 작동하지 않습니다.

분류에서Dev

Rails 4 JSON 속성 유형이 Postgres에서 작동하지 않습니다.

분류에서Dev

Rails 4에서 글꼴 변경이 작동하지 않습니다.

분류에서Dev

Rails 4에서 글꼴 변경이 작동하지 않습니다.

Related 관련 기사

  1. 1

    Rails 4 Bootstrap3 Dropdown이 작동하지만 작동하지 않습니다.

  2. 2

    파이썬에서 Tkinter 모듈을 사용하고 배경색 모듈이 작동하지 않습니다.

  3. 3

    .getjson이 MVc4에서 작동하지 않습니다.

  4. 4

    Bootstrap이 Rails 4에서 작동하지 않습니다.

  5. 5

    .profile이 xfce4에서 작동하지 않습니다.

  6. 6

    opencv2 Aruco 라이브러리 모듈이 파이썬에서 작동하지 않습니다.

  7. 7

    Eclipse RCP 3.x 플러그인이 Eclipse 4.x에서 올바르게 작동하지 않습니다.

  8. 8

    Simple_form 클래스 form-horizontal with bootstrap 3이 레일 4에서 작동하지 않습니다.

  9. 9

    Intel Core i3-4 * 그래픽이 Ubuntu 12.04에서 작동하지 않습니다.

  10. 10

    무선 어댑터 Broadcom [14e4 : 43a3]이 Ubuntu에서 작동하지 않습니다.

  11. 11

    무선 어댑터 Broadcom [14e4 : 43a3]이 Ubuntu에서 작동하지 않습니다.

  12. 12

    Sublime Text 3 용 Autoprefixer 모듈이 작동하지 않습니다.

  13. 13

    $ _GET이 drupal 모듈에서 작동하지 않습니다.

  14. 14

    shelve 모듈이 "with"문에서 작동하지 않습니다.

  15. 15

    파이썬에서 정렬이 작동하지 않습니다

  16. 16

    파이썬에서 모듈 netcdf4를 사용하여 NetCDF3 파일에 쓰기

  17. 17

    Rails 4-find_by_ *는 레이크 작업에서 작동하지 않습니다.

  18. 18

    jQuery 자동 완성이 Rails 4에서 작동하지 않습니다.

  19. 19

    Angular 4 애니메이션이 Edge에서 작동하지 않습니다.

  20. 20

    ( "") 인쇄가 파이썬에서 작동하지 않습니다.

  21. 21

    지도가 파이썬 3에서 예상대로 작동하지 않습니다.

  22. 22

    Spring MVC 4 서비스 @tTransactional이 작동하지 않습니다.

  23. 23

    MVC4에서 페이징이 작동하지 않습니다.

  24. 24

    파이썬 isfile이 여기서 작동하지 않습니다.

  25. 25

    Angular 4 Portal / CdkPortal이 새 자식 창에서 작동하지 않습니다.

  26. 26

    a4j : outputPanel에서 렌더링이 작동하지 않습니다.

  27. 27

    Rails 4 JSON 속성 유형이 Postgres에서 작동하지 않습니다.

  28. 28

    Rails 4에서 글꼴 변경이 작동하지 않습니다.

  29. 29

    Rails 4에서 글꼴 변경이 작동하지 않습니다.

뜨겁다태그

보관