"Python打印文件中随机一行,无重复"

2024-10-05 12:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小程序,从一个文本文件打印随机行。我想把已经选择的行保存在一个列表或其他东西中,这样下次就不会重复了。在

示例

text_database.txt

  1. This is a line
  2. This is an other line
  3. This is a test line
  4. That sucks

这是一个例子,说明输出是随机的,并且程序重复行–它是而不是终端中的直接输出:

This is a line
That sucks
That sucks
That sucks
This is a line

我的代码:

^{pr2}$

我尝试了:

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)

它不起作用,我需要帮助。谢谢你们。在


Tags: text程序示例列表thatislinerandom
3条回答
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)

我使用.read().splitlines()而不是.readlines()来清除每行的尾随空格(换行符)。我也可以这样做:

^{pr2}$

以下是文档中对random.sample的描述:

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

或者,您可以对行列表进行无序处理,然后对它们进行迭代。在

编辑-我想我现在明白了。怎么样?在

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())

这是一个非常混乱的解决方案,但我已经测试过了


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和列表长度之间的一个随机数,并打印与该数字对应的随机行

希望这有帮助!欢迎使用堆栈溢出

elif command == '/random':
    with open (text_database) as f:
        lines = f.readlines()

    while len(lines)>0:
        max_int = len(lines)-1 #update the len each loop as we remove one each time
        print(lines.pop(random.randint(0, max_int))) #pop a random value from the list

相关问题 更多 >

    热门问题