helm/bin/htmlent

37 lines
948 B
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
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', type=str, nargs="*", help="File to encode/decode")
2017-10-03 10:05:00 -07:00
opts.add_argument('-d', '--decode', action='store_true', help="Decode the given files/input")
args = opts.parse_args()
text = [line for line in fileinput.input(args.file)]
action = decode if args.decode else encode
print(action("\n".join(text).strip()))