-1
私はツイートのラベルをファイルに保存しようとしていますが、同時にこれらのラベルを端末に印刷してもうまくいきますが、ラベルはファイルに保存されていません。ここでなぜデータがファイルに保存されていないのですか?
が私のコードでラベルがファイルに保存されていないのはなぜ...ここ
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
...ですね。
または、私をガイドすることができます、それらを格納するための他の方法。
ファイルを開くためのキーワードでpythonを使ってみてください。また、csvの読み取りと書き込み操作のためのCSVライブラリ –
例外が発生しない場合は、ファイルに書き込むだけです。したがって、 'py_obj [" sentiment "] [" document "] [" label "]'はエラーを引き起こしています。ブランケット 'except'節でそのエラーが何であるかを正確にマスキングし、代わりにむしろあいまいで役に立たない' error'を表示します。 'py_obj'が何であるかを調べて、それを表示して、それがあなたが期待しているものかどうかを確認し、あなたの' try/except'を削除し、エラーを修正してください。 –