Advertisement
lswest

C&C 108 fcm-database.py

Apr 9th, 2016
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.55 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import os, json, datetime, re, csv
  3. # only necessary if you are using the drive CLI tool.
  4. from contextlib import contextmanager
  5. from subprocess import call
  6. # only necessary if you are using the drive CLI tool.
  7.  
  8. # general settings
  9. txtFile = os.path.join(os.path.expanduser("~"), "article-list.txt") # Target file name list.
  10. databaseFile = "fcm-database.json"
  11.  
  12. # article-list creation
  13. searchPaths = ['/home/lswest/Documents/GDrive/FCM', '/home/lswest/Dropbox/Articles/Full Circle Magazine/C&C'] # Must be list!
  14.  
  15. # for database creation
  16. dateStart = {100: datetime.date(2015, 8, 28)}
  17. entryTemplate = {-1: {}} # Template for the entry format - used in the update_database function.
  18.  
  19. if os.stat(databaseFile).st_size == 0:
  20.     db = {} # create a blank database if the json file is empty.
  21. else:
  22.     with open(databaseFile, 'r') as jsonFile:
  23.         db = json.load(jsonFile) # load the json file into a database, if not empty.
  24.     print("Database Loaded")
  25.  
  26. @contextmanager
  27. def cd(newdir):
  28.     """ This function is used to call a python equivalent of cd - just required for update_drive """
  29.     prevdir = os.getcwd()
  30.     os.chdir(os.path.expanduser(newdir))
  31.     try:
  32.         yield
  33.     finally:
  34.         os.chdir(prevdir)
  35.  
  36. def update_drive(drvPath):
  37.     """ This function is used to call the drive pull command - to update any changes to the folder.  If you don't use drive, just comment out the call to this function in main() """
  38.     with cd(drvPath):
  39.         call(["drive", "pull"])
  40.     return True
  41.  
  42. def dateFind(issue, startPoint):
  43.     """This function calculates the date based off the number issues to/from 100.  I.e. subtracts 2 months if considering issue 98."""
  44.     dateDiff = 100 - int(issue.replace("FCM", ""))
  45.     return (startPoint[100] - datetime.timedelta((dateDiff * 365) / 12)).isoformat()
  46.  
  47. def createArticleList(target, paths):
  48.     """This generates the text file containing all file names that should be included in the database.  Also does some basic cleanup (deletes .odt and changes Command & Conquer into C&C)"""
  49.     regexp = re.compile("FCM[0-9]+")
  50.     output = []
  51.     for path in paths:
  52.         files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and regexp.search(f) is not None and ".desktop" not in f]
  53.         output.append(files)
  54.     output = [item for sublist in output for item in sublist]
  55.     output = [w.replace(".odt", "") for w in output]
  56.     output = [w.replace("Command & Conquer", "C&C") for w in output]
  57.     output = set(output)
  58.     with open(target, 'w') as f:
  59.         for line in output:
  60.             f.write(line+"\n")
  61.     f.close()
  62.     return True
  63.  
  64.  
  65. def update_database(database, txtPath, entry):
  66.     """This function uses the text file created in createArticleList, and splits the file names into a dict object, which is added to the JSON database."""
  67.     with open(txtPath, 'r') as f:
  68.         for line in f.readlines():
  69.             if line != "\n":
  70.                 items = line.split(" - ")
  71.                 number = items[0].replace("FCM", "")
  72.                 entry[number] = {}
  73.                 entry[number]["issue"] = number
  74.                 if len(items) > 2:
  75.                     entry[number]["article"] = items[2].replace("\n", "")
  76.                 else:
  77.                     entry[number]["article"] = "Unknown"
  78.                 entry[number]["column"] = items[1]
  79.                 entry[number]["date"] = dateFind(items[0], dateStart)
  80.                 database.update(entry)
  81.         f.close()
  82.         del database[-1]
  83.         return database
  84.  
  85. def write_database(database, dbPath):
  86.     """Writes the database to the json file."""
  87.     with open(dbPath, 'w') as f:
  88.         f.write(json.dumps(database, indent=4))
  89.     return True
  90.  
  91. def write_csv_database(database, dbPath):
  92.     """For easy import into some spreadsheets programs, you can save the database as a CSV file as well."""
  93.     f = csv.writer(open(dbPath, "w"))
  94.  
  95.     allKeys = list(database["100"].keys()) # used to ensure values and keys match up.
  96.     f.writerow(allKeys)
  97.  
  98.     for key in database:
  99.         f.writerow([database[key][allKeys[0]], database[key][allKeys[1]], database[key][allKeys[2]], database[key][allKeys[3]]])
  100.  
  101. def main():
  102.     #update_drive(searchPaths[0])
  103.     createArticleList(txtFile, searchPaths)
  104.     dbN = update_database(db, txtFile, entryTemplate)
  105.     write_database(dbN, databaseFile)
  106.     #write_csv_database(db, "fcm-database.csv")
  107.  
  108. if __name__ == "__main__":
  109.     main() # Function is called, instead of inserting methods directly into this section.  Useful for eventual imports of the script.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement