简体   繁体   中英

Python Get Multiple Random Lines From File

Can some one help me with this real quick? Here is my code I am using:

# Lists:
anchorslist = []

#Files:
anchors = open(basepath + "anchors.txt", "r")

#Placed In List:
for line in anchors:
        anchorslist.append(line.replace("\n", "|"))

#Used:
type(anchorslist)

It will return a random line from my text file. What I want to achieve is getting let's say 10 random lines returned like this:

random_anchor1|random_anchor2|random_anchor3|random_anchor4

I'm using this for the random.

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

How would I modify the code to return that? Thanks.

 '|'.join(random.sample(anchorlist,10))

random.sample(anchorlist,10) return 10 random elements from anchorlist

'|'.join(...) concatenate the list using | as separator

what you want to use is the random python module. With that, you can use random.choice(anchorlist) to select a random line from the list. Here is some code that would achieve that:

import random
# Lists:
anchorslist = []

#Files:
anchors = open("anchors.txt", "r")

#Placed In List:
for line in anchors:
        anchorslist.append(line.replace("\n", "|"))

anchors.close()

rand_options = anchorslist  # duplicate list, better than editting the input list
rand_vals = []
length = 3  # configure to 10, or how ever many random lines you want

for _ in range(length):
    rand_val = random.choice(rand_options)
    rand_vals.append(rand_val)    
    rand_options.remove(rand_val)  # remove from list so you don't get duplicates (unless you don't mind those)

what_you_want = "".join(rand_vals).rstrip("|")

Say anchors.txt = "Hello \\n I \\n am \\n some \\n random \\n stuff", what_you_want = "I|stuff|Hello"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM