Guest User

BF4Stats Player Count Miner

a guest
Feb 21st, 2014
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. __AUTHOR__ = 'Beegie_B'
  2. __DATE__ = '2014-02-21'
  3.  
  4. import httplib, datetime, json
  5.  
  6. BF4STAT_URL = 'api.bf4stats.com'
  7. LOCATION = '/api/onlinePlayers?output=json'
  8. OUTFILE = 'bf4data.csv'
  9. TIMEFORMAT = '%Y-%m-%d %H:%M'
  10. KEYS = ['PC', 'PS3', 'PS4', 'X360', 'XONE']
  11.  
  12. def get_url_data(url, page):
  13.     conn = httplib.HTTPConnection(url)
  14.     conn.request("GET", page)
  15.     response = conn.getresponse()
  16.     return response.read()
  17.  
  18. def extract_player_counts(jstr):
  19.     data = json.loads(jstr)
  20.     counts = {}
  21.     counts['PC'] = str(data['pc']['count'])
  22.     counts['PS3'] = str(data['ps3']['count'])
  23.     counts['X360'] = str(data['xbox']['count'])
  24.     counts['XONE'] = str(data['xone']['count'])
  25.     counts['PS4'] = str(data['ps4']['count'])
  26.     return counts
  27.    
  28. def write_dict_to_csv(filename, d, keys=None, timestamp=False):
  29.     if keys is None:
  30.         keys = dict.keys()
  31.    
  32.     if timestamp:
  33.         keys = ['date'] + keys
  34.         d['date'] = datetime.datetime.now().strftime(TIMEFORMAT)
  35.        
  36.     include_header = False
  37.     try:
  38.         f = open(filename)
  39.         f.close()
  40.     except IOError:
  41.         include_header = True
  42.     finally:
  43.         f = open(filename, 'a')
  44.         if include_header:
  45.             f.write(', '.join(keys) + '\n')
  46.         f.write(', '.join([d[key] for key in keys]) + '\n')
  47.         f.close()
  48.    
  49. if __name__=='__main__':
  50.     data = get_url_data(BF4STAT_URL, LOCATION)
  51.     player_counts = extract_player_counts(data)
  52.     write_dict_to_csv(OUTFILE, player_counts, KEYS, timestamp=True)
Advertisement
Add Comment
Please, Sign In to add comment