Guest User

Untitled

a guest
Jan 27th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import json
  2. from watson_developer_cloud import NaturalLanguageUnderstandingV1
  3. from watson_developer_cloud.natural_language_understanding_v1 \
  4. import Features, EntitiesOptions, KeywordsOptions
  5. import time
  6. from datetime import timedelta
  7. import sys
  8. import os
  9. import argparse
  10.  
  11.  
  12. #We need to get our API credentials in the code for authentication that we have stored as Environment Variables locally
  13. NLP_USER_WATSON = os.environ.get("NLP_USER_WATSON")
  14. NLP_PASS_WATSON = os.environ.get("NLP_PASS_WATSON")
  15. NLP_VER_WATSON = os.environ.get("NLP_VER_WATSON")
  16.  
  17.  
  18. #Following line is used to save all the console output into a text file
  19. sys.stdout = open('nlp_api_output.txt', 'a')
  20.  
  21. start_time = time.monotonic()
  22.  
  23.  
  24. def input_file(text_file_path):
  25. global text
  26. if os.path.isfile(text_file_path):
  27. with open(text_file_path, 'r') as text_file:
  28. text = text_file.read()
  29. else:
  30. print("File doesn't exist in the directory!")
  31.  
  32.  
  33. def analyze_text():
  34. #Initialize NaturalLanguageUnderstanding function using the API credentials
  35. natural_language_understanding = NaturalLanguageUnderstandingV1(
  36. username = NLP_USER_WATSON,
  37. password = NLP_PASS_WATSON,
  38. version = NLP_VER_WATSON)
  39.  
  40. response = natural_language_understanding.analyze(
  41. text = text,
  42. features = Features(
  43. entities = EntitiesOptions(
  44. emotion = True,
  45. sentiment = True),
  46. keywords = KeywordsOptions(
  47. emotion = True,
  48. sentiment = True)))
  49.  
  50. print(json.dumps(response, indent = 2)) #json output after textual analysis
  51.  
  52.  
  53. if __name__ == '__main__':
  54. parser = argparse.ArgumentParser(
  55. description = __doc__,
  56. formatter_class = argparse.RawDescriptionHelpFormatter)
  57. parser.add_argument(
  58. 'text_file_path',
  59. help = 'The complete file path of the text file you want to analyze.')
  60. args = parser.parse_args()
  61.  
  62. input_file(args.text_file_path)
  63. analyze_text()
  64.  
  65.  
  66. end_time = time.monotonic()
  67. print("Execution_Time:", timedelta(seconds = end_time - start_time))
  68. print('\n')
Add Comment
Please, Sign In to add comment