-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab_6_looping_over_JSON.py
58 lines (48 loc) · 1.69 KB
/
lab_6_looping_over_JSON.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Standard Imports
import argparse
import json
# Third Party Imports
import boto3
# Arguments
parser = argparse.ArgumentParser(description="Provides translation between one source language and another of the same set of languages.")
parser.add_argument(
"--file",
dest="filename",
help="The path to the input file. The file should be valid JSON",
required=True)
args = parser.parse_args()
# Functions
def open_input():
""""This function returns a dictionary containing the contents of the Input section in the input file"""
with open(args.filename) as file_object:
contents = json.load(file_object)
return contents['Input']
# Boto3 function to use Amazon Translate to translate the text and only return the Translated Text
def translate_text(**kwargs):
client = boto3.client("translate")
response = client.translate_text(**kwargs)
print(response['TranslatedText'])
# Add a loop to iterate over the JSON file
def translate_loop():
input_text = open_input()
for item in input_text: # Here we iterate over all dictionaries in the Input List
translate_text(**item)
# Create a list of the input text
def new_input_text_list():
input_text = open_input()
new_list = []
for item in input_text:
text = item['Text']
new_list.append(text)
print(new_list)
def new_list_comprehension():
input_text = open_input()
list_comprehension = [item['Text'] for item in input_text] # Here we iterate over all dictionaries in the Input List
print(list_comprehension)
# Main Function - use to call other functions
def main():
new_input_text_list()
translate_loop()
new_list_comprehension()
if __name__ == "__main__":
main()