Python 3.x 如何从外部txt文件中获取随机行?

Python 3.x 如何从外部txt文件中获取随机行?,python-3.x,Python 3.x,所以,我想回答一个编码问题。它应该从一个外部文本文件创建一个随机的敲门笑话,但我不知道如何将笑话随机化。它只是打印出第一个笑话 以下是我的代码: # Saving filepath to a variable # makes a smoother transition to the Sandbox filepath = "KnockKnock.txt" # When finished copy all code after this line into the Sandbox # Open

所以,我想回答一个编码问题。它应该从一个外部文本文件创建一个随机的敲门笑话,但我不知道如何将笑话随机化。它只是打印出第一个笑话

以下是我的代码:

# Saving filepath to a variable
# makes a smoother transition to the Sandbox
filepath = "KnockKnock.txt"

# When finished copy all code after this line into the Sandbox

# Open the file as read-only
inFile = open(filepath, "r")

# Get the first line and do something with it
line = inFile.readline()

# Write your program below

print("Knock-Knock")
print("Who's there?")
print (line)
print(line + "who?")
line = inFile.readline()
print(line)
line = inFile.readline()

inFile.close()

你知道如何得到一个随机笑话而不是只做文件中的第一个吗?

假设你的文件
KnockKnock.txt
每隔一行就有两个笑话,那么我们可以将所有笑话读入一个包含设置和笑话行的2元组列表中

import random
...
# read in file and make a list of jokes
with open('KnockKnock.txt', 'r') as infile:
    # make a list of lines from file
    in_lines = infile.readlines()
    # pair every line with every other line - setup and punchline
    jokes = list(zip(in_lines[0::2], in_lines[1::2]))

# choose a random joke
setup, punchline = random.choice(jokes)

# print the joke
print("Knock-Knock")
print("Who's there?")
print(setup)
print(setup + " who?")
print(punchline)


为了更好地阅读并将所有行推送到列表中,请使用random.choice来选择一个随机行使用您的代码,Green Coep Guy,我得到了错误```回溯(最近一次调用):文件“main.py”,第8行,在笑话=列表中(zip(infie[0::2],infie[1::2])TypeError:“\io.TextIOWrapper”对象不是subscriptable@KadenReynolds很抱歉我在
zip()
中输入了错误的变量名。它应该引用
in_lines
变量,该变量刚刚列出了
infle
中的所有行。我已经编辑了解决方案来解决这个问题。