37 lines
924 B
Python
Executable file
37 lines
924 B
Python
Executable file
#!/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
|
|
|
|
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', type=str, nargs="*", help="File to encode/decode")
|
|
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()))
|