【发布时间】:2018-02-07 10:32:09
【问题描述】:
我希望能够从我的文件中随机打印多行。
这是我的文件:
1. What date did World War II start?
A. 20th October 1939
B. 1st September 1939
2. Which was a youth organisation group set up by Hitler during WWII for German youth?
A. Hitler Youth
B. Edelweiss Pirates
3. Who succeeded Elizabeth I on the English throne?
A. Henry VIII
B. James VI
4. Did Ireland take part in WWII?
A. No
B. Yes
5. Who was the Prime Minister of Britain at the start of WWII?
A. Neville Chamberlain
B. Winston Churchill
这是我当前的代码:
#Q1
with open ("hisEasyQ.txt") as hisEasyQFile:
for line in itertools.islice(hisEasyQFile, 0, 3):
print line
hisEasyA1 = raw_input("Enter your choice (A or B): ").lower()
print "\n"
#Q2
with open ("hisEasyQ.txt") as hisEasyQFile:
for line in itertools.islice(hisEasyQFile, 4, 7):
print line
hisEasyA2 = raw_input("Enter your choice (A or B): ").lower()
print "\n"
#Q3
with open ("hisEasyQ.txt") as hisEasyQFile:
for line in itertools.islice(hisEasyQFile, 8, 11):
print line
hisEasyA3 = raw_input("Enter your choice (A or B): ").lower()
print "\n"
#Q4
with open ("hisEasyQ.txt") as hisEasyQFile:
for line in itertools.islice(hisEasyQFile, 12, 15):
print line
hisEasyA4 = raw_input("Enter your choice (A or B): ").lower()
print "\n"
#Q5
with open ("hisEasyQ.txt") as hisEasyQFile:
for line in itertools.islice(hisEasyQFile, 16, 19):
print line
hisEasyA5 = raw_input("Enter your choice (A or B): ").lower()
print "\n"
目前,它按顺序打印文件,即:
1. What date did World War II start?
A. 20th October 1939
B. 1st September 1939
Enter your choice (A or B):
2. Which was a youth organisation group set up by Hitler during WWII for German youth?
A. Hitler Youth
B. Edelweiss Pirates
Enter your choice (A or B):
3. Who succeeded Elizabeth I on the English throne?
A. Henry VIII
B. James VI
Enter your choice (A or B):
4. Did Ireland take part in WWII?
A. No
B. Yes
Enter your choice (A or B):
5. Who was the Prime Minister of Britain at the start of WWII?
A. Neville Chamberlain
B. Winston Churchill
Enter your choice (A or B):
但是,我希望它在每次打开时随机打印行,如下所示:
1. Who was the Prime Minister of Britain at the start of WWII?
A. Neville Chamberlain
B. Winston Churchill
Enter your choice (A or B):
2. Who succeeded Elizabeth I on the English throne?
A. Henry VIII
B. James VI
Enter your choice (A or B):
#...etc...
然后当用户下次运行它时,问题的顺序就不同了。
知道如何使用 random 函数来执行此操作吗?
(我使用的是 Python 2.7)
【问题讨论】:
-
您好,欢迎来到 StackOverflow。请花一些时间阅读帮助页面,尤其是名为"What topics can I ask about here?" 和"What types of questions should I avoid asking?" 的部分。更重要的是,请阅读the Stack Overflow question checklist。您可能还想了解Minimal, Complete, and Verifiable Examples。
标签: python python-2.7 random text-files