2017-06-15 47 views
-5

我試圖對象提取到特定元素蟒蛇 - ValueError異常:無JSON對象可以被解碼

Traceback (most recent call last): 
    File "twitter_mining.py", line 17, in <module> 
    tweets_data = json.loads(tweets_data_path) 
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads 
    return _default_decoder.decode(s) 
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 

我的代碼時,此錯誤消息

tweets_data_path = 'data.txt' 
tweets_data = json.loads(tweets_data_path) 
tweets = pd.DataFrame() 
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data) 

數據 - http://intellij.my/rnd/nlp/sentiment-analysis/data.txt

請指教。謝謝。

+2

'json.loads'預計* JSON字符串*,不包含路徑可能包含JSON文件的字符串。 – deceze

回答

8

json.loads不接受文件名作爲參數。

閱讀文件的內容並將其傳遞給loads

tweets_data_path = 'data.txt' 
with open(tweets_data_path) as file: 
    tweets_data = json.loads(file.read()) 

或使用load

tweets_data_path = 'data.txt' 
with open(tweets_data_path) as file: 
    tweets_data = json.load(file) 
1

這應做到:

with open('data.txt') as tweets_data_path: 
    tweets_data = json.load(tweets_data_path) 
相關問題