Python multilevel madlibs spinner

mattseh

import this
Apr 6, 2009
5,504
72
0
A ~= A
Code:
def spin(text,brackets='[]'):
    """use "[choice1|choice2]" """
    open_marker = 0
    while text.find(brackets[0]) != -1:
        counter = 0
        for char in text:
            if char == brackets[0]:
                open_marker = counter
            if char == brackets[1]:
                part = text[open_marker+1:counter]
                words = part.split('|')
                word = random.choice(words)
                text = text.replace(brackets[0]+part+brackets[1],word,1)
                open_marker = 0
            counter += 1
    return text
might be useful to someone, usage: print spin('[[hi|hello]|[cya|goodbye]] [simon|meg|sumit][|!|?|.]')
 


Sorry, got distracted for a bit. Here's the same thing, just Ruby-fied:

Code:
class Spinner

    def spin(text, brackets = '{}')
        
        open_bracket = brackets[0,1]
        closed_bracket = brackets[1,1]
    
        open_marker = 0
        while text.include?(open_bracket)
            counter = 0
            
            text.each_char do |c|
                if c == open_bracket
                    open_marker = counter
                end
                if c == closed_bracket
                    part = text[open_marker+1..counter-1]
                    words = part.split('|')
                    
                    #python's random functions are way cooler than Ruby's
                    word = words[rand(words.length)]
                    
                    text.sub!("#{open_bracket}#{part}#{closed_bracket}", word)
                    open_marker = 0
                end
                
                counter += 1
            end
        end    
        
        return text    
    end
end
Does the same stuff as your previous script, I just wrapped it in a class because it's part of a larger script for my own stuff.
 
I'm pretty sure one of you wrote this but I have about 20 different php scripts for spinning in my scripts library. I wouldn't post my own monstrosity, was about 300 lines long.:party-smiley-004:

This was from angryaffiliate:
Code:
$spin_this = 'Some text {{{{{{was|used to be}}} in here|{{{goes|belongs}}} over there}}}';

function spin( $string ) {

	while ( preg_match( '/{{{([^{}]+)}}}/', $string, $matches ) ) {
		$pcs = explode( '|', $matches[1]);
		$string = str_replace($matches[0], $pcs[array_rand($pcs)], $string);
	}

	return $string;

}

for ($i=0;$i<10;$i++) {
	echo spin($spin_this),"\n";
}

And in perl by Gumby!:
Code:
use strict;
use warnings;

my $spinStr = 'Some text {{was|{used to be|{may|might} have been}} in here|{goes|belongs} over there}';

sub{for(my($t,$i,%h,@r)=$_[1];;){$_=$_[0];1 while(/{([^{}]+)}/ and @r=split(/\|/,$1) and s/{\Q$1\E}/$r[rand @r]/);!exists $h{$_}&&$_[2]->($_)&&$h{$_}++;last if (keys %h)==$t || ++$i>$t*100;}}->($spinStr,10,sub{print $_[0],"\n"});