User:Allanlw/navbox.py

From Wikipedia, the free encyclopedia
#!/usr/bin/python3

# Convert the [[List_of_Internet_phenomena]] page into a navbox
# the source code for that page should be saved as list.txt

import re

lines = open("list.txt", "r").read()

r1 = re.compile(r"(\* ?('''.*?''')|==(.*?)==)")
r2 = re.compile(r"\[\[.*?\]\]")

matches = r1.findall(lines)

# use list instead of dict to preserve ordering
groups = []

for tot,m1,m2 in matches:
  if len(m1) == 0:
    curgroup = m2.strip()
    groups.append((curgroup, []))
  else:
    groups[-1][1].append(m1.strip())

# remove non-links
groups = [(k, list(filter(lambda x: "[[" in x, v))) for (k, v) in groups]

# remove empty groups
groups = [(k,v) for (k,v) in groups if len(v) > 0]

print("""{{Navbox
| name  = Navbox/Memes
| title = [[Internet Meme|Internet Memes]]
| listclass = hlist
""")

i = 1

for name, els in groups:
  print ("| group{0} = {1}\n| list{0} = ".format(i, name))
  i += 1
  for el in els:
    ex = r2.findall(el)[0]
    print("*{0}".format(ex))

print("}}")