Hacker News new | ask | show | jobs
by ColinWright 2658 days ago
It's not really clear what you want to do, but here's some code I hacked out to see if it's the sort of thing you want:

    #!/usr/bin/python
    
    import random
    
    choices = {
        '[colour]' : [ 'red', 'green', 'blue', ],
        '[element]': [ 'antimony', 'arsenic', 'aluminum', 'selenium', ],
        }
    
    to_substitute = choices.keys()
    
    text_to_munge = 'Randomly, the colour of [element] is [colour].'
    
    for key in to_substitute:
    
        while key in text_to_munge:
    
            index_of_key = text_to_munge.index(key)
            head = text_to_munge[:index_of_key]
            tail = text_to_munge[index_of_key+len(key):]
            text_to_munge = head + random.choice(choices[key]) + tail
    
    print text_to_munge
It's really, really not good code, and the purpose of writing this is simply to ask in what ways it fails to meet your requirement. Do not use this code, it is not fit for deployment. If you are using a halfway decent language it will probably have facilities for the sort of thing you need, and using such facilities will be more efficient and effective than a hack like this.

So to repeat - don't use this code, but by all means, let us know the ways in which it fails to meet your requirement.