Recursive Python Spintax Class

Posted on October 4th, 2011

I did it in PHP, well here is the Python version. Using the Python version is just as easy as using the PHP version, and also has the same features as the PHP version. This class is open source, and free to use. I originally developed this Spintax Class for a Desktop Spintax Editor with syntax highlighting, which cannot be shared. Hope users find this class useful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Spintax:
   
    def __init__(self):
        return None
   
    def spin(self, str):
        while self.incomplete(str):
            str = self.regex(str)
        return str
       
    def regex(self, str):
        from random import choice
        match = self.preg_match("{[^{}]+?}", str)
        attack = match.split("|")
        new_str = self.preg_replace("[{}]", "", choice(attack))
        str = str.replace(match, new_str)
        return str
   
    def incomplete(self, str):
        import re
        complete = re.search("{[^{}]+?}", str)
        return complete
       
    def preg_match(self, pattern, subject):
        import re
        match = re.search(pattern, subject)
        return match.group()
   
    def preg_match_all(self, pattern, subject):
        import re
        matches = re.findall(pattern, subject)
        return matches
       
    def preg_replace(self, pattern, replacement, subject):
        import re
        result = re.sub(pattern, replacement, subject)
        return result

Leave a Reply

    To syntax highlight code just use [cc lang="whatever language here"]your code here[/cc]