sqt/sqt

80 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""
Converts plain quotes into html entities using Smartypants,
and from there to typographic quotes via html.unescape().
"""
import sys
import os
import smartypants
import html
def showhelp():
help = """
sqt (SmartQuotes)
================
Usage:
sqt infile [outfile]
Converts plain quotes to typographic quotes.
or:
sqt -h|--help
Shows this help message.
"""
print(help)
def convert_file(input_filename):
results = []
with open(input_filename, 'r') as infile:
for line in infile:
line = line.rstrip()
line_entities = smartypants.convert_quotes(line)
line_typographic = html.unescape(line_entities)
results.append(line_typographic)
return results
args = sys.argv
output_filename = None
# process command line arguments
if len(args) < 2:
print("\nError: you must specify an input file.")
showhelp()
sys.exit(1)
else:
input_filename = args[1]
if len(args) > 2:
output_filename = args[2]
if "-h" in args or "--help" in args:
showhelp()
sys.exit(0)
if not os.path.exists(input_filename):
print(f"\nError: the input file {input_filename} does not exist. Stopping.\n")
sys.exit(1)
if not os.access(input_filename, os.R_OK):
print(f"\nError: you do not have read permission for {input_filename}. Stopping.\n")
sys.exit(1)
cleaned_lines = convert_file(input_filename)
if output_filename is not None:
print(f"Writing to {output_filename} ...")
with open(output_filename, 'w') as out_file:
for line in cleaned_lines:
out_file.write(f"{line}\n")
print("... done")
else:
for line in cleaned_lines:
print(line)