Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Made a better one -> http://pastebin.com/ZYphBFP5
- #
- # AiE story breaker
- #
- #
- #
- # Author:
- # Date: 12/Sep/2013
- # License: GNU General Public License
- #
- # Purpose:
- # Split a collection of lines of text into parts, all under
- # a certain character limit
- #
- # Usage:
- # aiebreaker.py <file to split> <maxiumum character per part>
- from sys import argv
- from os.path import dirname,join,basename,isdir
- from os import mkdir,getcwd,chdir
- # Script function
- def run(args):
- # If the argument list does not contain 2 arguments
- # alert the user, and exit
- if len(args) != 3:
- print 'bad argument list'
- print 'usage: aiebreaker.py <filename> <maximum character limit>'
- return
- else:
- # Retreive the arguments
- filename = args[1]
- try:
- part_length = int(args[2])
- except:
- # If the part length is not an integer, alert the user and exit
- print 'bad part length'
- print 'usage: aiebreaker.py <filename> <maximum character limit>'
- return
- current_length = 0
- # Try to open the file and read its contents
- try:
- with open(filename, 'r') as f:
- input_text = f.read()
- except:
- # If the file cannot be opened, alert the user and exit
- print 'bad filename'
- print 'usage: aiebreaker.py <filename> <maximum character limit>'
- return
- # Split the text into lines
- lines = input_text.split('\n')
- # Create a list of parts
- parts = []
- parts.append([])
- # For each line in the file
- for line in lines:
- # If the line itself is too long for the maximum character limit,
- # alert the user and exit
- if len(line) > part_length:
- print line + ' : line too long, exiting'
- # Otherwise
- else:
- # If the line would make the current part too long,
- # Create a new part
- to_append = line+'\n'
- if current_length + len(to_append) > part_length:
- parts.append([])
- print 'breaking at '+str(current_length)
- current_length = 0
- # Add the line to the current part
- parts[-1].append(to_append)
- current_length += len(to_append)
- # Make a directory for the parts
- base_name = basename(filename)
- extension = base_name.split('.')[-1]
- if len(extension) == 0:
- bare_name = base_name
- else:
- extension = '.'+extension
- bare_name = base_name[0:-len(extension)]
- parts_dir = join(dirname(filename),bare_name+'_parts')
- if not isdir(parts_dir):
- mkdir(parts_dir)
- cwd = getcwd()
- chdir(parts_dir)
- # Then make a file in that directory for each part
- current_part = 0
- for part in parts:
- with open(bare_name+"_part_"+str(current_part)+extension, 'w') as f:
- for line in part:
- f.write(line)
- current_part += 1
- chdir(cwd)
- # End of process
- # Invoke the Script
- run(argv)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement