2013-05-13 9 views
6

ho convogliato l'uscita del mio script Python che accede tweet di Twitter in tempo reale in un file output.txt utilizzando:lettura file di testo di nuovo in un dizionario usando json.loads

$python scriptTweet.py > output.txt 

In origine, l'output restituito dallo script era un dizionario che è stato scritto in un file di testo.

Ora voglio utilizzare il file output.txt per accedere ai tweet memorizzati in esso. Ma quando uso questo codice per analizzare il testo in output.txt in un dizionario Python usando json.loads():

tweetfile = open("output.txt") 
pyresponse = json.loads('tweetfile.read()') 
print type(pyresponse) 

Questo errore si apre:

pyresponse = json.loads('tweetfile.read()') 
    File "C:\Python27\lib\json\__init__.py", line 326, in loads 
    return _default_decoder.decode(s) 
    File "C:\Python27\lib\json\decoder.py", line 366, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 

Come devo convertire il contenuto di file output.txt di nuovo in un dizionario?

risposta

9

'tweetfile.read()' è una stringa così come la vedi. Si desidera chiamare questa funzione:

with open("output.txt") as tweetfile: 
    pyresponse = json.loads(tweetfile.read()) 

o leggerla direttamente utilizzando json.load e lasciare jsonread sul tweetfile stesso:

with open("output.txt") as tweetfile: 
    pyresponse = json.load(tweetfile) 
+6

Oppure utilizzare 'json.load (tweetfile)'. Perché avere un cane e abbaiare da solo? –

+0

@eumiro Ho aggiornato il codice. Viene visualizzato questo errore: File "getTweet.py", riga 24, in pyresponse = json.load (tweetfile) File "C: \ Python27 \ lib \ json \ __ init__.py", riga 278, in carico * * kw) File "C: \ Python27 \ lib \ json \ __ init__.py", riga 326, nei carichi return _default_decoder.decode (s) File "C: \ Python27 \ lib \ json \ decoder.py", riga 369, in decodifica raise ValueError (errmsg ("Dati aggiuntivi", s, end, len (s))) ValoreErrore: Dati aggiuntivi: riga 2 colonna 1 - riga 21 colonna 1 (char 124 - 56517) – learner123

+0

@techfreak - inserisci un esempio del tuo 'output.txt' - potrebbe esserci un problema. – eumiro

Problemi correlati