I have a little program which prints random lines from a text file. I want to save the the already chosen lines in a list or something else, so it don't will repeat next time.
Example
text_database.txt
- This is a line
- This is an other line
- This is a test line
- That sucks
This is an example to show that the output is random and the program repeats lines – it is not the direct output in the terminal:
This is a line
That sucks
That sucks
That sucks
This is a line
My code:
# Variable for text file
text_database = './text_database.txt'
...
with open (text_database) as f:
lines = f.readlines()
print(random.choice(lines))
What I tried:
with open (text_database) as f:
lines_list = []
lines = f.readlines()
random_tmp = random.choice(lines)
if random_tmp not in lines_list:
lines_list.append(random_tmp)
print(random_tmp)
It doesn't work and I need help. Thank you guys.
from random import sample
file_name = "text_database.txt"
lines = open(file_name, "r").read().splitlines()
for line in sample(lines, k=len(lines)):
print(line)
I use .read().splitlines()
instead of .readlines()
to purge the trailing whitespace (newlines) from each line. I could have also done:
lines = [line.rstrip("\n") for line in open(file_name, "r")]
Here is a description of random.sample
from the documentation:
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Alternatively, you could have shuffled your list of lines, and then iterated over them.
EDIT - I think I understand now. How's this?
def main():
from random import shuffle
file_name = "text_database.txt"
lines = open(file_name, "r").read().splitlines()
shuffle(lines)
sentinel = object()
def command_random():
try:
line = lines.pop()
except IndexError:
print("There are no more lines in the file!")
else:
print(line)
def command_quit():
nonlocal sentinel
sentinel = None
commands = {
"random": command_random,
"quit": command_quit
}
while sentinel is not None:
user_input = input("Please enter a command: ")
command = commands.get(user_input)
if command is None:
continue
command()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
this is a REALLY messy solution but i have tested this beforehand
f = open(text_database, "r")
list = []
list_of_nums = []
for i in f:
list.append(i)
elif command == '/random':
randomNum = random.randint(0, len(list) - 1)
def reRun():
global randomNum
for i in list_of_nums:
if randomNum == i:
randomNum = random.randint(0, len(list) - 1)
reRun()
reRun()
list_of_nums.append(randomNum)
print(list[randomNum])
What this code deos is go throgh all the lines in f and put them in a list. than it choses a random number bettween 0 and the lenght of the list and prints a random line corresponding to that number
Hope this helps! And welcome to stack overflow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With