Last active
June 27, 2020 13:28
-
-
Save tomschr/d8e25e480ba66465f9d35effdd85b768 to your computer and use it in GitHub Desktop.
Creates nested entities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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