|
| 1 | +import json |
| 2 | +# ///////////////////////////////// |
| 3 | +# This is name of file that will be processed |
| 4 | +file_path = "output.json" |
| 5 | +# ///////////////////////////////// |
| 6 | + |
| 7 | +# make list out of output.json file |
| 8 | +def process_json_file(): |
| 9 | + encodings_to_try = ['utf-8', 'iso-8859-1', 'windows-1252'] |
| 10 | + for encoding in encodings_to_try: |
| 11 | + try: |
| 12 | + with open(file_path, 'r', encoding=encoding) as file: |
| 13 | + file_content = file.read() |
| 14 | + file_content = file_content.strip() |
| 15 | + data = json.loads(file_content) |
| 16 | + print(f"Successfully loaded JSON data from {file_path} using {encoding} encoding") |
| 17 | + return data |
| 18 | + except UnicodeDecodeError: |
| 19 | + print(f"Couldn't decode with {encoding}, trying next encoding...") |
| 20 | + except json.JSONDecodeError as e: |
| 21 | + print(f"Error decoding JSON data: {e}") |
| 22 | + print("Hint: Make sure the file contains valid JSON. Each object should be separated by commas.") |
| 23 | + return None |
| 24 | + except Exception as e: |
| 25 | + print(f"An unexpected error occurred: {e}") |
| 26 | + return None |
| 27 | + |
| 28 | + print("Error: Unable to decode the file with any of the attempted encodings.") |
| 29 | + return None |
| 30 | + |
| 31 | + |
| 32 | +if __name__ == "__main__": |
| 33 | + # Make list from file 'output.json' |
| 34 | + problem_list = process_json_file() |
| 35 | + |
| 36 | + # map to store the tags and number of problems |
| 37 | + problem_tags = {} |
| 38 | + |
| 39 | + # Count topics and no. of problems in the list |
| 40 | + total_problems = 0 |
| 41 | + sum_of_types = 0 |
| 42 | + for x in problem_list: |
| 43 | + for tag in x["tags"]: |
| 44 | + if tag in problem_tags: |
| 45 | + problem_tags[tag] += 1 |
| 46 | + else: |
| 47 | + problem_tags[tag] = 1 |
| 48 | + sum_of_types+=1 |
| 49 | + total_problems+=1 |
| 50 | + |
| 51 | + |
| 52 | + # make the dict to json format with indentation of 4 |
| 53 | + json_str = json.dumps(problem_tags, indent=4) |
| 54 | + print(json_str) |
| 55 | + |
| 56 | + print(f"Total problems {total_problems}") |
| 57 | + print(f"Total types of problems {sum_of_types}") |
| 58 | + |
0 commit comments