我正在尝试将推文的标签存储在一个文件中,同时我在终端上打印这些标签并且它工作正常,但标签不存储在文件中。
这是我的代码......
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
为什么标签不存储在文件中?
或者你可以指导我,任何其他存储它们的方法。