#!/usr/bin/env python3
"""
Encode/decode HTML entities in stdin or given file(s).
"""
import argparse
import fileinput
import html
from html.entities import entitydefs
from pathlib import Path
ENTITIES = {value: key for key, value in entitydefs.items()}
def encode(text):
t = ""
for c in text:
if c in ENTITIES:
t += "&" + ENTITIES[c] + ";"
else:
t += c
return t
def decode(text):
return html.unescape(text)
if __name__ == '__main__':
opts = argparse.ArgumentParser(description="Encodes (or decodes) HTML entities in text.")
opts.add_argument('file', nargs="?", help="File to encode/decode")
opts.add_argument('-d', '--decode', action='store_true', help="Decode the given files/input")
args = opts.parse_args()
if "file" in args and args.file:
text = Path(args.file).read_text()
else:
text = "\n".join([line for line in fileinput.input()]).strip()
if args.decode:
print(decode(text))
else:
print(encode(text))