2017-06-16 66 views
-1

我試圖將tweet的標籤存儲在一個文件中,同時我在終端上打印這些標籤,它工作正常,但標籤不存儲在文件中。爲什麼數據沒有存儲在文件中?

這裏是我的代碼...

import requests 
import json 

username = "****" 
password = "****" 

def start(): 
    header = { 'Content-Type':'application/json',} 

    parameters = { 
     ('version','2017-02-27'), 
    } 

    url = 'https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze' 

    tw = open('/home/darkhorse/Desktop/ML/refine_tweets.csv','r') 
    labeling = open('/home/darkhorse/Desktop/ML/tweets_label.csv','w') 
    for tweet in tw: 
     Data = { "text":tweet,"features":{ "sentiment":{"document":True } } } 
     # changing Data dict to str form 
     Data = json.dumps(Data) 

     r = requests.post(url, headers=header, params=parameters, data=Data, auth=(username, password)) 

     # r.content is a byte object so there is need to change it into str 
     str_obj =r.content.decode("utf-8") 

     # changing str to python obj dict. 
     py_obj = json.loads(str_obj) 

     try: 
      print(py_obj["sentiment"]["document"]["label"]) 
      labeling.write(py_obj["sentiment"]["document"]["label"]) 
      labeling.write('\n') 
     except: 
      print('error') 
      # labeling.write('error\n') 

    labeling.close() 
    tw.close() 


if __name__ == '__main__': 
    start() 

下面是排名前12位的鳴叫和他們的標籤..

1. AreEnglishbacktoplayingtheiroldbrandofcricket, neutral 
2. Match6:After43.0Ov,England250/6.JosButtler28(25b),AdilRashid4(7b), neutral 
3. Yesurright....wecan'thopeatall\r, neutral 
4. BlowtotheUmmah., negative 
5. VeryimpressivesideNewZealand, neutral 
6. ENGvsNZ|CT2017|Overs43|ENG250-6|Buttler28*Rashid4*|Bowler:Southee112411\n, neutral 
7. WhyisEnglandhosting, neutral 
8. Latest:2\ufe0f\u20e35\ufe0f\u20e30\ufe0f\u20e3up250/6after43oversv, error 
9. 250upforEnglandwithdrizzlearoundafter43overs, neutral 
10. , error 
11. Latest:2\ufe0f\u20e35\ufe0f\u20e30\ufe0f\u20e3up250/6after43oversv, error 
12. Match6:JosButtlerhitsTimSoutheefora4!248/6(42.4Ov), neutral 

爲什麼標籤不能在文件中存儲?

或者你可以引導我,任何其他方法來存儲它們。

+0

嘗試使用python和關鍵字來打開文件。還有csv庫,用於csv讀寫操作 –

+0

如果沒有異常發生,那麼您只是在寫文件...所以'py_obj [「sentiment」] [「document」] [「label」]'導致錯誤,你正在用你的blanket'except'子句掩蓋那個錯誤,而是顯示一個相當模糊和無用的'error'。通過打印來檢查「py_obj」是什麼,看看它是否是你期望的,暫時刪除你的「try/except」並糾正錯誤。 –

回答

0

使用庫facebook-sdk。 它可以讓你做你想做的事在facebook內

相關問題