Skip to content

Instantly share code, notes, and snippets.

@green-s
Last active August 29, 2015 14:23
Show Gist options
  • Save green-s/bb696dc6f52b532be19f to your computer and use it in GitHub Desktop.
Save green-s/bb696dc6f52b532be19f to your computer and use it in GitHub Desktop.
Format a given text file as Source Engine aliases.
import sys
import argparse
ALIAS_DECLARATION = "alias {script_name} {script_name}0"
ALIAS_PREFIX = "alias {script_name}{line_number} \""
ALIAS_SUFFIX = "alias {script_name} {script_name}{next_line_number}"
def main(argv):
args = parse_args()
script_name = args.input_file.name.split('.')[0]
input_text = args.input_file.readlines()
args.input_file.close()
split_lines = [list(string_split_length(line.rstrip().replace('"', "''"), 127)) for line in input_text]
processed_lines = []
for line_number, split_line in enumerate(split_lines):
line_prefix = ALIAS_PREFIX.format(
script_name = script_name,
line_number = line_number)
line_content = '; '.join('say ' + part for part in split_line) + '"; '
next_line_number = line_number + 1 if line_number < len(split_lines) - 1 else 0
line_suffix = ALIAS_SUFFIX.format(
script_name = script_name,
next_line_number = next_line_number)
processed_line = line_prefix + line_content + line_suffix
processed_lines.append(processed_line)
alias_declaration = ALIAS_DECLARATION.format(script_name = script_name)
args.output_file.write(alias_declaration + "\n\n")
for line in processed_lines:
args.output_file.write(line + "\n")
args.output_file.close()
print("Done.\n")
#print(repr(processed_lines))
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('input_file', type=argparse.FileType('r'), help="The input file.")
parser.add_argument('output_file', type=argparse.FileType('w'), help="The output file.")
return parser.parse_args()
def string_split_length(string, length):
return (string[0+i:length+i] for i in range(0, len(string), length))
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment