@@ -253,12 +253,61 @@ def entity_sentiment_file(gcs_uri):
253
253
print (u'Sentiment: {}\n ' .format (entity .sentiment ))
254
254
255
255
256
+ # [START def_classify_text]
257
+ def classify_text (text ):
258
+ """Classifies content categories of the provided text."""
259
+ client = language .LanguageServiceClient ()
260
+
261
+ if isinstance (text , six .binary_type ):
262
+ text = text .decode ('utf-8' )
263
+
264
+ document = types .Document (
265
+ content = text .encode ('utf-8' ),
266
+ type = enums .Document .Type .PLAIN_TEXT )
267
+
268
+ categories = client .classify_text (document ).categories
269
+
270
+ for category in categories :
271
+ print (u'=' * 20 )
272
+ print (u'{:<16}: {}' .format ('name' , category .name ))
273
+ print (u'{:<16}: {}' .format ('confidence' , category .confidence ))
274
+ # [END def_classify_text]
275
+
276
+
277
+ # [START def_classify_file]
278
+ def classify_file (gcs_uri ):
279
+ """Classifies content categories of the text in a Google Cloud Storage
280
+ file.
281
+ """
282
+ client = language .LanguageServiceClient ()
283
+
284
+ document = types .Document (
285
+ gcs_content_uri = gcs_uri ,
286
+ type = enums .Document .Type .PLAIN_TEXT )
287
+
288
+ categories = client .classify_text (document ).categories
289
+
290
+ for category in categories :
291
+ print (u'=' * 20 )
292
+ print (u'{:<16}: {}' .format ('name' , category .name ))
293
+ print (u'{:<16}: {}' .format ('confidence' , category .confidence ))
294
+ # [END def_classify_file]
295
+
296
+
256
297
if __name__ == '__main__' :
257
298
parser = argparse .ArgumentParser (
258
299
description = __doc__ ,
259
300
formatter_class = argparse .RawDescriptionHelpFormatter )
260
301
subparsers = parser .add_subparsers (dest = 'command' )
261
302
303
+ classify_text_parser = subparsers .add_parser (
304
+ 'classify-text' , help = classify_text .__doc__ )
305
+ classify_text_parser .add_argument ('text' )
306
+
307
+ classify_text_parser = subparsers .add_parser (
308
+ 'classify-file' , help = classify_file .__doc__ )
309
+ classify_text_parser .add_argument ('gcs_uri' )
310
+
262
311
sentiment_entities_text_parser = subparsers .add_parser (
263
312
'sentiment-entities-text' , help = entity_sentiment_text .__doc__ )
264
313
sentiment_entities_text_parser .add_argument ('text' )
@@ -309,3 +358,7 @@ def entity_sentiment_file(gcs_uri):
309
358
entity_sentiment_text (args .text )
310
359
elif args .command == 'sentiment-entities-file' :
311
360
entity_sentiment_file (args .gcs_uri )
361
+ elif args .command == 'classify-text' :
362
+ classify_text (args .text )
363
+ elif args .command == 'classify-file' :
364
+ classify_file (args .gcs_uri )
0 commit comments