Advertisement
HittingSmoke

Planet List Converter

Jun 16th, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. import re
  2. import json
  3. count=1 # Counter
  4. # Regex to isolate data from document into named capture groups
  5. rtrregex = "^(?:(?:\s+\d+\:\s+(?P<jumpDistance>[0-9]+\.[0-9]{2})\s)|\s+)(?P<systemName>\S+.*(?=\s\|\s))\s\|\s(?P<planetName>(?<=\s\|\s).+(?=\s\())\s\((?P<planetDistance>(?<=\()\d+(?=\)))\)\s(?P<planetType>[A-Z]{3})$"
  6. jsonfile = open('planetList.json', 'w') # JSON output filename
  7. jsonoutput = []
  8. with open('list.txt') as f: # Open original document and split into lines
  9.     for line in f:
  10.         if re.match(rtrregex, line): # Ignore lines that do not contain a match to the regex
  11.             rtrclean = re.match(rtrregex, line) # Strip all but the data matching the capture groups
  12.             rtrdict = rtrclean.groupdict()# Convert matches to dict named after capture groups
  13.             if not rtrdict['jumpDistance']: # Make null values in this key 0
  14.                 rtrdict['jumpDistance'] = 0
  15.             rtrdict['num'] = count # Every object will be numbered sequentially
  16.             rtrdict['jumpDistance'] = float(rtrdict['jumpDistance']) # Convert string containing number with decimal to float
  17.             rtrdict['planetDistance'] = int(rtrdict['planetDistance']) # Convert string containing number to int
  18.             rtrdict['planetName'] = rtrdict['systemName']+" "+rtrdict['planetName'] # Prepend systemName value to planetName value
  19.             jsonoutput.append(rtrdict) # Add dictionary object to jsonoutput list
  20.             count = count+1 # Increase count by one for next loop
  21.             #rtrjson = json.dumps(rtrdict) # Debugging
  22.             #print(rtrjson) # Debugging
  23.  
  24. json.dump(jsonoutput, jsonfile, separators=(',',':')) # Write completed list to JSON file, minified
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement