Skip to content

Commit d490cd6

Browse files
committed
Adding Sentence class in language implementation.
Also adding a from_api_repr() method for parsing it from the API.
1 parent 44d9faa commit d490cd6

2 files changed

Lines changed: 66 additions & 0 deletions

File tree

gcloud/language/test_token.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,34 @@ def test_from_api_repr(self):
9191
self.assertEqual(token.edge_index, edge_index)
9292
self.assertEqual(token.edge_label, edge_label)
9393
self.assertEqual(token.lemma, lemma)
94+
95+
96+
class TestSentence(unittest.TestCase):
97+
98+
def _getTargetClass(self):
99+
from gcloud.language.token import Sentence
100+
return Sentence
101+
102+
def _makeOne(self, *args, **kw):
103+
return self._getTargetClass()(*args, **kw)
104+
105+
def test_constructor(self):
106+
content = "All the king's horses."
107+
begin = 11
108+
sentence = self._makeOne(content, begin)
109+
self.assertEqual(sentence.content, content)
110+
self.assertEqual(sentence.begin, begin)
111+
112+
def test_from_api_repr(self):
113+
klass = self._getTargetClass()
114+
content = 'All the pretty horses.'
115+
begin = -1
116+
payload = {
117+
'text': {
118+
'content': content,
119+
'beginOffset': begin,
120+
},
121+
}
122+
sentence = klass.from_api_repr(payload)
123+
self.assertEqual(sentence.content, content)
124+
self.assertEqual(sentence.begin, begin)

gcloud/language/token.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,38 @@ def from_api_repr(cls, payload):
166166
lemma = payload['lemma']
167167
return cls(text_content, text_begin, part_of_speech,
168168
edge_index, edge_label, lemma)
169+
170+
171+
class Sentence(object):
172+
"""A Google Cloud Natural Language API sentence object.
173+
174+
.. _Sentence message: https://cloud.google.com/natural-language/reference\
175+
/rest/v1beta1/documents/annotateText#Sentence
176+
177+
See `Sentence message`_.
178+
179+
:type content: str
180+
:param content: The text that the sentence is composed of.
181+
182+
:type begin: int
183+
:param begin: The beginning offset of the sentence in the original
184+
document according to the encoding type specified
185+
in the API request.
186+
"""
187+
188+
def __init__(self, content, begin):
189+
self.content = content
190+
self.begin = begin
191+
192+
@classmethod
193+
def from_api_repr(cls, payload):
194+
"""Convert a sentence from the JSON API into a :class:`Sentiment`.
195+
196+
:param payload: dict
197+
:type payload: The value from the backend.
198+
199+
:rtype: :class:`Sentence`
200+
:returns: The sentence parsed from the API representation.
201+
"""
202+
text_span = payload['text']
203+
return cls(text_span['content'], text_span['beginOffset'])

0 commit comments

Comments
 (0)