Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active June 27, 2020 13:28
Show Gist options
  • Select an option

  • Save tomschr/d8e25e480ba66465f9d35effdd85b768 to your computer and use it in GitHub Desktop.

Select an option

Save tomschr/d8e25e480ba66465f9d35effdd85b768 to your computer and use it in GitHub Desktop.
Creates nested entities
#!/usr/bin/env python3
#
"""
<!ENTITY a "aaaaaa">
<!ENTITY b "&a;">
<!ENTITY c "&c;">
...
<!ENTITY z "&y;">
"""
import itertools
import sys
__author__ = "Tom Schraitle"
def pairwise(iterable):
"""
Iterate pairwise over an iterable
s -> (s0, s1), (s1, s2), (s2, s3), ...
"""
a, b = itertools.tee(iter(iterable), 2)
next(b, None)
return zip(a, b)
def chain(n:int):
"""
Chain the pairwise tuples
n=1 -> ("a", "b"), ("b", "c"), ...
n=2 -> ("aa", "ab"), ("ab", "ac"), ...
"""
az = [chr(c) for c in range(ord('a'), ord('z')+1)]
s_az = "".join(az)
it = pairwise(itertools.product(az, repeat=n))
for a, b in it:
yield "".join(a), "".join(b)
def entities(n:int, inittext:str):
"""
Create lines with <!ENTITY name "value">
"""
tmpl = '<!ENTITY {a} "{t}">'
it = chain(n)
ent, nxt = next(it)
# Create first two items manually
yield tmpl.format(a=ent, t=inittext)
yield tmpl.format(a=nxt, t="&{};".format(ent))
for ent, nxt in it:
yield tmpl.format(a=nxt, t="&{};".format(ent))
def get(index:int, default):
"""
Extract information from sys.argv; if index is not available in
sys.argv, return default
"""
try:
return sys.argv[index]
except IndexError:
return default
if __name__ == "__main__":
n = int(get(1, 1))
inittext = get(2, "aaaaa")
for ent in entities(n, inittext):
print(ent)
# eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment