Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions language/google/cloud/language/syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
breaks a document down into tokens and sentences.
"""

from google.cloud.language.sentiment import Sentiment


class PartOfSpeech(object):
"""Part of speech of a :class:`Token`."""
Expand Down Expand Up @@ -183,11 +185,19 @@ class Sentence(object):
:param begin: The beginning offset of the sentence in the original
document according to the encoding type specified
in the API request.

:type sentiment: :class:`~google.cloud.language.sentiment.Sentiment`
:param sentiment:
(Optional) For calls to
:meth:`~google.cloud.language.document.Document.annotate_text` where
``include_sentiment`` is set to true, this field will contain the
sentiment for the sentence.
"""

def __init__(self, content, begin):
def __init__(self, content, begin, sentiment=None):
self.content = content
self.begin = begin
self.sentiment = sentiment

@classmethod
def from_api_repr(cls, payload):
Expand All @@ -200,4 +210,11 @@ def from_api_repr(cls, payload):
:returns: The sentence parsed from the API representation.
"""
text_span = payload['text']
return cls(text_span['content'], text_span['beginOffset'])

try:
sentiment = Sentiment.from_api_repr(payload['sentiment'])
except KeyError:
sentiment = None

return cls(text_span['content'], text_span['beginOffset'],
sentiment=sentiment)
25 changes: 25 additions & 0 deletions language/unit_tests/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,28 @@ def test_from_api_repr(self):
sentence = klass.from_api_repr(payload)
self.assertEqual(sentence.content, content)
self.assertEqual(sentence.begin, begin)
self.assertEqual(sentence.sentiment, None)

def test_from_api_repr_with_sentiment(self):
from google.cloud.language.sentiment import Sentiment
klass = self._get_target_class()
content = 'All the pretty horses.'
begin = -1
score = 0.5

This comment was marked as spam.

This comment was marked as spam.

magnitude = 0.5
payload = {
'text': {
'content': content,
'beginOffset': begin,
},
'sentiment': {
'score': score,
'magnitude': magnitude,
}
}
sentence = klass.from_api_repr(payload)
self.assertEqual(sentence.content, content)
self.assertEqual(sentence.begin, begin)
self.assertIsInstance(sentence.sentiment, Sentiment)
self.assertEqual(sentence.sentiment.score, score)
self.assertEqual(sentence.sentiment.magnitude, magnitude)