spikem
spikem

Reputation: 173

Printing random number of words per line

I'm just trying to write a simple script that prints between 1 and 10 words per line from a source. I know this should be super simple but I'm having a brain fart. This is my best guess:

import random

s = open("somefile.txt").readlines()

for line in s:
    line.strip()
    rand_int = rand.randint(1,10)
    sentence = ''.join(s,rand_int)
    print sentence

Specifically, I'm just having trouble figuring out how to tell python print a random group of words a random number of times per line. Is this something a list comprehension might help with?

I'd appreciate any help you could give. Thank you!

Upvotes: 1

Views: 569

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208505

Try the following:

import random

with open("somefile.txt", "rb") as f:
    for line in f:
        print ' '.join(random.sample(line.strip().split(), random.randint(1, 10)))

Here is a portion of the documentation of random.sample():

random.sample(population, k)
    Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

So we can create population by splitting the line on whitespace, and then randomize k, which should give you what you are looking for.

Upvotes: 2

Related Questions