Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A simple way with <a href="http://docs.python.org/library/re.html?highlight=re.sub#re.subn" rel="nofollow noreferrer">re.subn</a>, which can also accept a function instead of a replacement string:</p> <pre><code>import re from random import randint def select(m): choices = m.group(1).split('|') return choices[randint(0, len(choices)-1)] def spinner(s): r = re.compile('{([^{}]*)}') while True: s, n = r.subn(select, s) if n == 0: break return s.strip() </code></pre> <p>It simply replaces all the deepest choices it meets, then iterates until no choice remains. <code>subn</code> returns a tuple with the result and how many replacements were made, which is convenient to detect the end of the processing.</p> <p>My version of <code>select()</code> can be replaced by Bobince's that uses <code>random.choice()</code> and is more elegant if you just want to stick to a random selector. If you want to build a choice tree, you could extend the above function, but you will need global variables to keep track of where you are, so moving the functions into a class would make sense. This is just a hint, I won't develop that idea since it was not really the orginial question.</p> <p>Note finally that you should use <code>r.subn(select, s, re.U)</code> if you need unicode strings (<code>s = u"{...}"</code>)</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; s = "{{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}}" &gt;&gt;&gt; print spinner(s) 'farewell n3wbz' </code></pre> <hr> <p><strong>Edit:</strong> Replaced <code>sub</code> by <code>subn</code> to avoid infinite loop (thanks to Bobince to point it out) and make it more efficient, and replaced <code>{([^{}]+)}</code> by <code>{([^{}]*)}</code> to extract empty curly brackets as well. That should make it more robust to ill-formatted patterns.</p> <p>For people who like to put as much as possible on one line (which I personally wouldn't encourage):</p> <pre><code>def spin(s): while True: s, n = re.subn('{([^{}]*)}', lambda m: random.choice(m.group(1).split("|")), s) if n == 0: break return s.strip() </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload