user1495755
user1495755

Reputation: 33

pull out element data random range from list

I want to pull out list element amount random range (from 5 to 15). for example, I have text which contain following string

locasari2
jyprin
a0007a
hdki22
binarykorea
onlineforum
vobank1
chsb4322
gaiber62
wjun2104
inaekkim
zcbm22
happy_sex
ckdgns0524
lhe0925
chong4787
multy26
ver_test
danaecco
paoo
kea2209
ybyng234
smrush
kimksh2596
winproto
cs8489
aek5262
bktan12
puripink04
qkdlfjf99
nyj4154
joara5778
keepro
sswpsh72
tom770303
ckdanrl0757
himart26
lco3924
heloword
jking15

and I want to extract a list of elements randomly from 5 to 15 so what I want to get result is,

locasari2,jyprin,a0007a,hdki22,binarykorea
onlineforum,vobank1,chsb4322,gaiber62,wjun2104,inaekkim,zcbm22
ckdgns0524,lhe0925,chong4787,multy26,ver_test,danaecco
paoo,kea2209,ybyng234,smrush,kimksh2596,winproto,cs8489,aek5262,bktan12,puripink04,qkdlfjf99,nyj4154
joara5778,keepro,sswpsh72,tom770303,ckdanrl0757,himart26,lco3924,heloword

This is what I did until now but one of problem is sometimes can correctly extract amount elements but sometimes over extract data more than 15 words

out = ''
handle = open('fx -01.txt').read()

for i, line in enumerate(handle.split('\n')):
    out +=  line + ','
    rndind = random.randint(5,15)
    if (i + 1) %  rndind == 0 :
    out = out.split(',')
    print len(out)
    print out
    out = ''

Sorry for my bad English.

Upvotes: 3

Views: 441

Answers (2)

Aaron Hall
Aaron Hall

Reputation: 395933

You want to use the context manager.

To loop through this, let's assume you're dealing with a small resulting list (although the file might be huge), and memory for the choice list isn't an issue, we'll collect the items first in a list and then loop through random selections of items in it.

import random
choice_list = []
with open('fx -01.txt', 'rU') as handle:
    first = 5
    last = 15
    for i in xrange(last):
        selection = handle.next()
        if first <= i <= last:
            choice_list.append(selection)

number_of_random_choices = 10
for i in xrange(number_of_random_choices):
    print random.choice(choice_list)

The context manager ensures you automatically close the file in case there's an error, so you don't leave the file locked open.

open provides you with an iterator, and the U (for Universal) in the mode flag ensures you split on the newlines regardless of your platform, Windows or Unix.

We then avoid materializing the entire file or even the iterator into a list in memory and select just the list we want to make random selections from. Demonstrated is looping through it 10 times. Each selection will be independent of the previous, meaning each can be selected more than once.

To give them all in random positions, i.e. shuffle them randomly in place:

random.shuffle(choice_list)
print choice_list

will give you a list of them all shuffled randomly.

Upvotes: 0

falsetru
falsetru

Reputation: 369474

Using itertools.islice, you don't need to read the whole file.

import itertools
import random

with open('fx-01.txt') as f:
    while True:
        n = random.randint(5, 15)
        elements = [line.strip() for line in itertools.islice(f, n)]
        # itertools.islice(f, n): to fetch `n` lines from file.
        if not elements:
        # if len(elements) < 5: # Use this if you want drop trailing <5 lines.
            break
        print(','.join(elements))

Upvotes: 1

Related Questions