def random_comment():
with open('comments.txt', 'r') as f:
comments = [line.strip() for line in f]
comment = random.choice(comments)
return comment
Asked
Active
Viewed 49 times
1
-
Don't choose them one by one, take a `random.sample(comments, number_you_want)` – Thierry Lathuille Jul 07 '21 at 14:59
1 Answers
1
Read all the comments once (before calling random). Then in the random_comment(), chose a random comment from your list and remove it from the list.
all_comments = []
with open('comments.txt', 'r') as f:
all_comments.append([line.strip() for line in f])
def random_comment(all_comments):
index = random.randint(0,len(all_comments))
result = all_comments.pop(index)
return result, all_comments

Jules Civel
- 449
- 2
- 13
-
-
This has a major drawback, though: you need to regenerate the complete list if you want to take another sample. – Thierry Lathuille Jul 07 '21 at 15:00
-
``` import random class Comments: def __init__(self, file_path): with open('comments.txt', 'r') as f: self.comments = random.shuffel([line.strip() for line in f]) self.position = 0 def random_comment(self): comment = self.comment[self.position] position += 1 return comment myComments = Comments("file_path") randomComment = myComments.random_comment() ``` – FloLie Jul 07 '21 at 15:04
-
@ThierryLathuille no you don't, you return the updated list. And you take the list as parameter so you just have to pass the last returned list. – Jules Civel Jul 07 '21 at 15:06
-
-
Yes, you do. Try it with `all_comments = ["A", "B", "C"] ; res, comm = random_comment(all_comments) ; print(res, all_comments)`. It prints `B ['A', 'C']`. You only mutate the original list that your function got as argument, and never create a new one. – Thierry Lathuille Jul 07 '21 at 15:14
-
i'm getting this error: randint() missing 1 required positional argument: 'b' – Landry N. Jul 07 '21 at 15:22
-
Oh ok, i thought you meant that you have to read it all again every time. You are indeed right, we should use pop instead. I'll edit my answer. – Jules Civel Jul 07 '21 at 15:22
-