Created
October 18, 2019 23:12
-
-
Save chidindu-ogbonna/3a38769beaa8e3b1c22599c024137cbe to your computer and use it in GitHub Desktop.
Google Cloud Natural Language API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from google.cloud import language_v1 | |
from google.cloud.language_v1 import enums | |
from google.auth import compute_engine | |
def analyze_sentiment(text): | |
""" | |
Analyze sentiment in a text | |
Args: | |
text -> The content to be analyzed | |
""" | |
try: | |
client = language_v1.LanguageServiceClient().from_service_account_json( | |
"./service_account_key.json" | |
) | |
except FileNotFoundError: | |
credentials = compute_engine.Credentials() | |
client = language_v1.LanguageServiceClient(credentials=credentials) | |
type_ = enums.Document.Type.PLAIN_TEXT | |
language = "en" | |
encoding_type = enums.EncodingType.UTF8 | |
document = {"content": text, "type": type_, "language": language} | |
response = client.analyze_sentiment(document, encoding_type=encoding_type) | |
# Get overall sentiment | |
document_sentiment = response.document_sentiment | |
score = document_sentiment.score | |
sentiment = assign_sentiment(score) | |
return sentiment | |
def classify_text(text): | |
"""Classify shop category using shop bio | |
""" | |
try: | |
client = language_v1.LanguageServiceClient().from_service_account_json( | |
"./service_account_key.json" | |
) | |
except FileNotFoundError: | |
credentials = compute_engine.Credentials() | |
client = language_v1.LanguageServiceClient(credentials=credentials) | |
type_ = enums.Document.Type.PLAIN_TEXT | |
language = "en" | |
document = {"content": text, "type": type_, "language": language} | |
response = client.classify_text(document) | |
for category in response.categories: | |
print(u"Category name: {}".format(category.name)) | |
print(u"Confidence: {}".format(category.confidence)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment