Guest User

Untitled

a guest
May 21st, 2018
1,058
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. import csv
  2. import json
  3.  
  4. '''
  5. Example structure
  6. {
  7. "Canada": {
  8. "export-countries": {
  9. "China": 15800000000.0,
  10. "Japan": 8090000000.0,
  11. ...
  12. },
  13. "import-countries": {
  14. "China": 27300000000.0,
  15. "Germany": 10600000000.0,
  16. ...
  17. },
  18. ...
  19.  
  20. exports.csv
  21. -----------
  22. root,node,count
  23. Canada,China,15800000000
  24. Canada,Japan,8090000000
  25.  
  26. imports.csv
  27. -----------
  28. root,node,count
  29. Canada,China,27300000000,
  30. Canada,Germany,10600000000.0,
  31.  
  32. '''
  33.  
  34. G8 = set(["Canada", "China", "France", "Germany", "Italy", "Japan", "Russia", "United Kingdom", "United States"])
  35.  
  36. def create_links(origin_country, countries, result):
  37. for country in countries:
  38. if country in G8:
  39. value = int(countries[country])
  40. result.append([origin_country, country, value])
  41.  
  42. def process_data(data):
  43.  
  44. exports = []
  45. imports = []
  46.  
  47. for country in data:
  48. country_data = data[country]
  49. export_countries = country_data['export-countries']
  50. import_countries = country_data['import-countries']
  51.  
  52. create_links(country, export_countries, exports)
  53. create_links(country, import_countries, imports)
  54.  
  55. return {
  56. "exports" : exports,
  57. "imports" : imports
  58. }
  59.  
  60. def write_csv(filename, data):
  61. with open(filename, 'w') as csvfile:
  62. fieldnames = ['root', 'node', 'count']
  63. writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  64. writer.writeheader()
  65.  
  66. for row in data:
  67. writer.writerow({'root': row[0], 'node': row[1], 'count' : row[2]})
  68.  
  69. data_file = open('g8-trade.json', 'r')
  70. data = json.load(data_file)
  71.  
  72. processed = process_data(data)
  73.  
  74. write_csv('exports.csv', processed['exports'])
  75. write_csv('imports.csv', processed['imports'])
Add Comment
Please, Sign In to add comment