2015-06-26 23 views
22

Mentre il porting del codice python2-3, ottengo questo errore durante la lettura da un URLerrore python3: valore_iniziale deve essere str o Nessuno

TypeError: initial_value must be str or None, not bytes.

import urllib 
import json 
import gzip 
from urllib.parse import urlencode 
from urllib.request import Request 


service_url = 'https://babelfy.io/v1/disambiguate' 
text = 'BabelNet is both a multilingual encyclopedic dictionary and a semantic network' 
lang = 'EN' 
Key = 'KEY' 

    params = { 
     'text' : text, 
     'key' : Key, 
     'lang' :'EN' 

     } 

url = service_url + '?' + urllib.urlencode(params) 
request = Request(url) 
request.add_header('Accept-encoding', 'gzip') 
response = urllib.request.urlopen(request) 
if response.info().get('Content-Encoding') == 'gzip': 
      buf = StringIO(response.read()) 
      f = gzip.GzipFile(fileobj=buf) 
      data = json.loads(f.read()) 

L'eccezione viene generata in questa linea

buf = StringIO(response.read()) 

Se uso python2, funziona correttamente.

+0

È possibile fornire un traceback completo? –

+0

Dà solo questo errore e si ferma. TypeError: initial_value deve essere unicode o None, non str – AMisra

+0

puoi includere il valore della tua variabile 'url'? quando provo con 'url = 'http: // www.google.com'' il codice funziona perfettamente per me – maxymoo

risposta

7

Questo appare come un altro python3 bytes vs. str problema. La tua risposta è di tipo bytes (che è diverso in python 3 da str). Devi prima inserirla in una stringa usando response.read().decode('utf-8') e poi usare StringIO su di essa. O potresti voler usare BytesIO come qualcuno ha detto - ma se ti aspetti che sia str, il modo preferito è quello di decode in un str prima.

+0

È contenuto di codifica gzip non di testo. – tynn

+1

Quindi 'BytesIO' è una buona idea. – gabhijit