Reputation: 173
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.
Upvotes: 0
Views: 521
Reputation: 658
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"
Upvotes: 2
Reputation: 3608
'|'.join(random.sample(anchorlist,10))
random.sample(anchorlist,10)
return 10 random elements from anchorlist
'|'.join(...)
concatenate the list using |
as separator
Upvotes: 3