Python Get Multiple Random Lines From File -


can 1 me real quick? here code using:

# lists: anchorslist = []  #files: anchors = open(basepath + "anchors.txt", "r")  #placed in list: line in anchors:         anchorslist.append(line.replace("\n", "|"))  #used: type(anchorslist) 

it return random line text file. want achieve getting let's 10 random lines returned this:

random_anchor1|random_anchor2|random_anchor3|random_anchor4 

i'm using random.

def type(name):     value = name[random.randint(0,len(name)-1)]     return value 

how modify code return that? thanks.

what want use random python module. that, can use random.choice(anchorlist) select random line list. here code achieve that:

import random # lists: anchorslist = []  #files: anchors = open("anchors.txt", "r")  #placed in list: line in anchors:         anchorslist.append(line.replace("\n", "|"))  anchors.close()  rand_options = anchorslist  # duplicate list, better editting input list rand_vals = [] length = 3  # configure 10, or how ever many random lines want  _ in range(length):     rand_val = random.choice(rand_options)     rand_vals.append(rand_val)         rand_options.remove(rand_val)  # remove list don't duplicates (unless don't mind those)  what_you_want = "".join(rand_vals).rstrip("|") 

say anchors.txt = "hello \n \n \n \n random \n stuff", what_you_want = "i|stuff|hello"


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -