helm/bin/htmlent

44 lines
1 KiB
Plaintext
Raw Normal View History

2017-07-03 08:47:33 -07:00
#!/usr/bin/env python3
2017-10-03 10:05:00 -07:00
"""
Encode/decode HTML entities in stdin or given file(s).
"""
2017-07-03 08:47:33 -07:00
2017-10-03 10:05:00 -07:00
import argparse
2017-07-03 08:47:33 -07:00
import fileinput
import html
from html.entities import entitydefs
2017-10-03 10:05:00 -07:00
from pathlib import Path
2017-07-03 08:47:33 -07:00
ENTITIES = {value: key for key, value in entitydefs.items()}
2017-10-03 10:05:00 -07:00
2017-07-03 08:47:33 -07:00
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__':
2017-10-03 10:05:00 -07:00
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))