0%

Python从文件中打印不重复的随机行

❓ 我有一个程序,可以从文本文件中打印随机行。 我想将已经选择的行保存在列表或其他内容中,因此下次不再重复。例:

1
2
3
4
5
6
text_database.txt

This is a line
This is an other line
This is a test line
That sucks

这是重复行的示例,它不是终端中的直接输出:

1
2
3
4
5
This is a line
That sucks
That sucks
That sucks
This is a line

我的代码:

1
2
3
4
5
6
7
8
# Variable for text file
text_database = './text_database.txt'

...

with open (text_database) as f:
lines = f.readlines()
print(random.choice(lines))

我试过的

1
2
3
4
5
6
7
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)

它不起作用,我需要帮助。


✔️ 这是一个非常凌乱的解决方案,但我已经事先测试过

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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])

这段代码的含义是遍历f中的所有行并将它们放在列表中。 然后它选择一个介于0到列表长度之间的随机数,并打印与该数字相对应的随机行。