2013-05-13 32 views
6

我管道我Python腳本的輸出,訪問Twitter的直播鳴叫到文件output.txt的使用:本來使用閱讀文本文件回字典json.loads

$python scriptTweet.py > output.txt 

,由腳本返回的輸出是一個被寫入文本文件的字典。

現在我想使用output.txt文件來訪問存儲在其中的推文。但是,當我使用json.loads()在output.txt中使用此代碼來解析文本到Python字典:

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

此錯誤彈出:

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 

我應該如何轉換內容文件output.txt再次轉換成字典?

回答

9

'tweetfile.read()'是一個字符串,因爲你看到它。你要調用這個函數:

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

或直接使用json.load閱讀,讓在tweetfile本身jsonread

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

或者使用'json.load(tweetfile)'。爲什麼要養一隻狗並吠叫自己? – 2013-05-13 12:40:07

+0

@eumiro我更新了代碼。這個錯誤彈出:文件「getTweet.py」,第24行,在 pyresponse = json.load(tweetfile) 文件「C:\ Python27 \ lib \ json \ __ init__.py」,第278行,載入中 * * kw) 文件「C:\ Python27 \ lib \ json \ __ init__.py」,第326行,載入中 return _default_decoder.decode(s) 文件「C:\ Python27 \ lib \ json \ decoder.py」,第369行,解碼 raise ValueError(errmsg(「Extra data」,s,end,len(s))) ValueError:額外數據:第2行第1行 - 第21行第1列(char 124 - 56517) – learner123 2013-05-13 12:54:04

+0

@techfreak - 發佈你的'output.txt'的例子 - 可能有問題。 – eumiro 2013-05-13 13:02:16