-#!/bin/bash
-set -ex
-cd ~/
-file=".aspell.en.pws"
-header=$(head -1 ${file} | sed 's: [0-9]* *$::')
-(
-sed 1d ${file}
-printf '%s\n' "$@"
-) | LC_ALL=en_US sort -u | sed '/^[[:space:]]*$/d' > ${file}.tmp
-(
-echo "${header} $(wc -l ${file}.tmp | awk '{print $1}') "
-cat ${file}.tmp
-) > ${file}
-mv ${file}.tmp ".config/google-chrome/Custom Dictionary.txt"
+#!/usr/bin/env python3
+
+"""Update & sort personal dictionaries."""
+
+import argparse
+import locale
+import os
+import sys
+
+
+def get_parser():
+ """Return a CLI parser."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('words', nargs='*',
+ help='words to add to the dictionary')
+ return parser
+
+def main(argv):
+ parser = get_parser()
+ opts = parser.parse_args(argv)
+
+ locale.setlocale(locale.LC_COLLATE, 'en_US.UTF8')
+
+ home = os.path.expanduser('~')
+
+ # Pull out the current set of words.
+ pws = os.path.join(home, '.aspell.en.pws')
+ with open(pws, encoding='utf-8') as fp:
+ lines = [x.strip() for x in fp.readlines()]
+ header = lines[0]
+ assert header.startswith('personal_ws-1.1 en ')
+ words = set(lines[1:])
+
+ # Add any words from the user.
+ words.update(opts.words)
+
+ # Update the aspell dict.
+ words = sorted(words, key=locale.strxfrm)
+ header = 'personal_ws-1.1 en %s ' % (len(words),)
+ with open(pws, 'w', encoding='utf-8') as fp:
+ fp.write(header + '\n')
+ fp.write('\n'.join(words) + '\n')
+
+ # Update Chrome's dict.
+ chrome_pws = os.path.join(home, '.config', 'google-chrome', 'Custom Dictionary.txt')
+ with open(chrome_pws, 'w', encoding='utf-8') as fp:
+ fp.write('\n'.join(words) + '\n')
+
+
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))