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:
|
2017-12-17 22:12:13 -08:00
|
|
|
if c in ENTITIES:
|
|
|
|
t += "&" + ENTITIES[c] + ";"
|
|
|
|
else:
|
|
|
|
t += c
|
2017-07-03 08:47:33 -07:00
|
|
|
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.")
|
2017-12-05 22:39:10 -08:00
|
|
|
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()
|
|
|
|
|
2017-12-05 22:39:10 -08:00
|
|
|
text = [line for line in fileinput.input(args.file)]
|
|
|
|
action = decode if args.decode else encode
|
|
|
|
print(action("\n".join(text).strip()))
|