Last active
November 10, 2018 17:59
-
-
Save erm3nda/12d8867795a117d8b5e40e7571b8ec3c to your computer and use it in GitHub Desktop.
Python nested spintax parser
This file contains 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/local/env/ python | |
# -*- coding:utf-8 -*- | |
''' | |
This is a basic yet powerfull re function to parse any spintax text. | |
Works with nested curly brackets. | |
''' | |
import re, random | |
def spinner(s): | |
''' | |
Example of 3 level nested spintax text | |
s = "hola {soy|me llamo} {{juan|juanito}|{jose|{pepe|pepelu}}}" | |
''' | |
while True: | |
s, n = re.subn('{([^{}]*)}', | |
lambda m: random.choice(m.group(1).split("|")), | |
s) | |
if n == 0: break | |
return s.strip() | |
if __name__ == "__main__": | |
s = "hola {soy|me llamo} {{juan|juanito}|{jose|pepe}}" | |
for i in range(0,2): | |
print(spinner(s)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment