Thursday, July 3, 2014

Improved Script

I decided to get a little fancy with the "random PDF" script from my last post.

I modified the random selection element to be weighted based on age. I decided to start simple by simply dividing file age (in days) by 10 (I'll try using the log next), rounding up (using math.ceil) and randomly selecting from a new array (called "weighted_files") which gives more weight to older files. Basically: I want it to be more likely that an older file is opened rather than a newer file. My reading model has now shifted to a FIFO scheme.

Here it is, with a few comments.


#! /usr/bin/python
import time, os, math, sys, shutil
from random import randint
clear = lambda: os.system('cls')
clear()
path = '[DIRECTORY WITH PDF FILES IN IT]'

pdf_files = [f for f in os.listdir(path) if f.endswith('.pdf')]

len_pdf_files = len(pdf_files)
if len_pdf_files == 0:
print ("No PDF files found!")
time.sleep(3)
sys.exit(0)

pdf_ages = []

for pdf_file in pdf_files:
os.rename(os.path.join(path, pdf_file), os.path.join(path, pdf_file.replace(' ', '_')))
file_loc = path + '/' + pdf_file
file_age_sec = time.time() - os.path.getmtime(file_loc)
file_age_days = file_age_sec/60/60/24
file_age_days_round = math.floor(file_age_days)
pdf_ages.append(file_age_days_round)
# Build an array for use in weighted random selection
weighted_files = []
weighting_factor = 10 # arbitrary
for index, pdf_age in enumerate(pdf_ages):
weight = math.ceil(pdf_age/weighting_factor)

# Adds the index number (from pdf_ages, which should match pdf_files) in proportion to the weight
for i in range(0,weight):
weighted_files.append(index) 

len_weighted_files = len(weighted_files)
rand_int = randint(0,len_weighted_files-1)
pdf_files_index = weighted_files[rand_int]
file_name_str = str(pdf_files[pdf_files_index])

file_loc_str = path + '/' + file_name_str
pdf_cmd_str = "start " + file_loc_str
os.system(pdf_cmd_str)
valid_command = 0
while valid_command == 0 :
delete_file = input("Delete file? Y or N: ")
if (delete_file == "Y" or delete_file == "y"):
os.remove(file_loc_str)
print (file_name_str + " has been deleted! Good work!")
new_num_pdfs = len_pdf_files - 1
new_num_pdfs_str = str(new_num_pdfs)
print ("There are now ",new_num_pdfs_str," PDFs remaining.")
time.sleep(3)
valid_command = 1
sys.exit(0)
elif (delete_file == "N" or delete_file == "n"):
print ("Fine then, but next time, delete it!")
dest_folder_loc_str = 'D:/Users/a27m8mt/Documents/Things_To_Read/Hold_for_later/'
shutil.move(file_loc_str,dest_folder_loc_str)
print (file_name_str + " has been moved to the holding folder: " + dest_folder_loc_str)
time.sleep(3)
valid_command = 1
sys.exit(0)
else:
print ("Invalid command. Try again.")

No comments: