已安装的套餐google云语言: sudo pip install --upgrade google-cloud-language
在本地目录中创建文档:// inbound-byte-154607-ml / sentiment1.txt副本
为文档的情感分析运行此脚本:
#!/usr/bin/env python
from google.cloud import language
def sentiment_file(gcs_uri):
"""Detects sentiment in the file located in Google Cloud Storage."""
language_client = language.Client()
# Instantiates a plain text document.
document = language_client.document_from_url(gcs_uri)
# Detects sentiment in the document. You can also analyze HTML with:
# document.doc_type == language.Document.HTML
sentiment = document.analyze_sentiment()
print('Score: {}'.format(sentiment.score))
print('Magnitude: {}'.format(sentiment.magnitude))
if __name__ == "__main__":
sentiment_file("gs://inbound-byte-154607-ml/Copy of sentiment1.txt")
错误面临:
Traceback (most recent call last):
File "./analyze-sentiment.py", line 22, in <module>
sentiment_file("gs://inbound-byte-154607-ml/Copy of sentiment1.txt")
File "./analyze-sentiment.py", line 14, in sentiment_file
sentiment = document.analyze_sentiment()
File "/usr/local/lib/python2.7/dist- packages/google/cloud/language/document.py", line 188, in analyze_sentiment
File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 335, in api_request
error_info=method + ' ' + url)
google.cloud.exceptions.Forbidden: 403 Google Cloud Natural Language API has not been used in project cloud-devshell-dev before or it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/language.googleapis.com/overview?project=cloud-devshell-dev then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry. (POST https://language.googleapis.com/v1/documents:analyzeSentiment)
method='POST', path='analyzeSentiment', data=data)
File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 335, in api_request
error_info=method + ' ' + url)
google.cloud.exceptions.Forbidden: 403 Google Cloud Natural Language API has not been used in project cloud-devshell-dev before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/language.googleapis.com/overview?project=cloud-devshell-dev then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry. (POST https://language.googleapis.com/v1/documents:analyzeSentiment)