Reputation: 63
If file.txt contains:
appple
cheese
cake
tree
pie
Using this:
nameFile = ("/path/to/file.txt")
nameLines = open(nameFile).read().splitlines()
randomName = random.choice(nameLines)
This will only print 1 line from file.txt
How would I print 1-2 lines (randomly)?
Example:
first output = apple
second output = cheesetree
third output = piecake
fourth output = cake
Upvotes: 3
Views: 787
Reputation: 2261
Do you want an even probability among all of the outputs?
Assuming order doesn't matter and n
lines in the text file, this means you want to choose from n + n(n-1)/2 = n(n+1)/2
different outcomes. That is (n+1) choose 2
. If you set an empty value as the additional outcome, then you will get the correct distribution.
Thus:
nameFile = ("/path/to/file.txt")
nameLines = open(nameFile).read().splitlines()
nameLines.append("")
randomName = "".join(random.sample(nameLines, 2))
This is always choosing a random.sample
of two, but one of the values could be the empty string that was added. This will be as if you just choose one single value.
If you don't actually want an even distribution of all of the possible outcomes, then you would first want to choose if you want 1 or 2, then choose from the list of names accordingly.
Upvotes: 1
Reputation: 1121764
To produce more than one random number, use random.sample()
. You can randomize the sample size:
randomNames = random.sample(nameLines, random.randint(1, 2))
This gives you a list with either 1 or 2 items, picked as a random sample from the input.
Demo:
>>> import random
>>> nameLines = '''\
... apple
... cheese
... cake
... tree
... pie
... '''.splitlines()
>>> random.sample(nameLines, random.randint(1, 2))
['apple', 'cake']
>>> random.sample(nameLines, random.randint(1, 2))
['cheese']
Use str.join()
to join the words together, if needed:
>>> ' '.join(random.sample(nameLines, random.randint(1, 2)))
'pie cake'
>>> ' '.join(random.sample(nameLines, random.randint(1, 2)))
'cake'
Upvotes: 4
Reputation: 17168
You have two basic options, depending on (let's say you're in a two-line case) whether you want to pick two random lines, or any random line twice. That is, whether or not duplicates are allowed.
If you want to allow duplicates, you need to pick a randint
first, and then run the code you already have that many times. This is "pick a random line, a random number of times."
# print one or two random lines: possibly the same line twice!
for i in range(random.randint(1, 2)): # change the upper bound as desired
print(random.choice(nameLines))
In the other case use random.sample
and then print all the results. This is "pick a random number of discrete lines".
# print one or two distinct elements, chosen at random from nameLines
for line in random.sample(nameLines, random.randint(1, 2)):
print(line)
Use the appropriate one for your use case!
Upvotes: 1