Advertisement
ChallengerAppeared

aiebr2.py

Dec 21st, 2013
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.28 KB | None | 0 0
  1. from os import mkdir,getcwd
  2. from os.path import join,dirname,isdir
  3. from sys import argv
  4. from math import log10,pow
  5.  
  6. # Check for the correct number of agruments
  7. # Print a help message if they are incorrect
  8. if len(argv) != 3:
  9.     print 'syntax: python aiebr2.py <maximum characters> <file to split>'
  10.     print 'NOTE: The maximum characters does not account for post links, or'
  11.     print 'part numbering, please account for this when choosing a length'
  12. else:
  13.  
  14.     # Interpret the user input
  15.     max_chars = int(argv[1])
  16.     file_to_split = argv[2]
  17.  
  18.     # Read the story as a collection of lines
  19.     story = []
  20.     story_length = 0;
  21.     with open(file_to_split, 'r') as story_file:
  22.         while True:
  23.             line = story_file.readline()
  24.             if line != "":
  25.                 story.append(line)
  26.                 story_length += len(line)
  27.             else:
  28.                 break
  29.  
  30.     # Build a set of parts by adding each line to a part, creating a
  31.     #   new part if adding that line would go over the maximum character
  32.     #   limit
  33.     parts = []
  34.     current_length = 0
  35.     current_part = ""
  36.     for line in story:
  37.         if current_length+len(line) > max_chars:
  38.             parts.append(current_part)
  39.             current_part = line
  40.             current_length = len(line)
  41.         else:
  42.             current_part += line
  43.             current_length += len(line)
  44.     if current_part != "":
  45.         parts.append(current_part)
  46.  
  47.     # Create a directory for the parts
  48.     total_parts = len(parts)
  49.     story_dir = dirname(file_to_split);
  50.     if story_dir == "":
  51.         story_dir = os.getcwd()
  52.     parts_dir = join(story_dir,file_to_split+'_parts')
  53.     if not isdir(parts_dir):
  54.         mkdir(parts_dir)
  55.  
  56.     # For each part, make a file in that directory with the contents
  57.     #   as well as a x/y numbering at the bottom
  58.     for i in range(0,len(parts)):
  59.         part = parts[i]
  60.         part_path = join(parts_dir, str(i+1)+'.txt')
  61.         with open(part_path,'w') as part_file:
  62.             numbering = '\n'+str(i+1)+'/'+str(total_parts)
  63.             to_write = part+numbering
  64.             chars_written = len(to_write)
  65.             part_file.write(to_write)
  66.             print 'part '+str(i+1)+ ' is '+str(chars_written)+ ' characters long'
  67.  
  68.     print 'done'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement