所以我有一个充满琐事问题的文档。这是一个:
Category: Definitions
Question: A word like 'NASA' formed from the initials of other words is a(n) ······.
Answer: acronym
大约有3000个问题,我想随机回答一个问题。我将如何做到这一点并获得:
A word like 'NASA' formed from the initials of other words is a(n) ······.
在一个名为问题的变量中。 然后是另一个问题的答案。 希望有道理。
答案 0 :(得分:1)
如果我把您的文件看成类似于以下内容:
Category: Category 1
Question: Question 1
Answer: Answer 1
Category: Category 2
Question: Question 2
Answer: Answer 2
Category: Category 3
Question: Question 3
Answer: Answer3
...
然后我们可以执行以下操作。
如果您以行列表的形式读取文件:
with open("myfile.txt", "r") as f:
list_of_lines = f.readlines()
从这里您可以找到文档中所有行的列表。 然后,您可以按索引访问问题和答案,因为下一个问题/答案等的索引会比上一个问题的索引+3。
例如,对于上面的示例文件,我们可以使用以下命令打印问题答案对:
for i in range(1, len(list_of_line)-2, 3):
question = list_of_lines[i]
answer = list_of_lines[i+1]
print(question, answer)
希望您的文件看起来类似,或者您可以使用此处的想法将其应用于特定情况
答案 1 :(得分:1)
linereader
模块提供了访问文件中随机行的高效简便方法。假设您的文件结构为:
Category: Definitions
Question: 1
Answer: 1
Question: 2
Answer: 2
Question: 3
Answer: 3
这是一个简单的代码段,可从文件中随机获取Question
和Answer
:
from linereader import getline
from random import randint
length = 7
filename = 'a.txt'
random_number = randint(2, length-2)
line_1 = getline(filename, random_number)
if line_1.startswith('Question:'):
line_1 = line_1.strip('Question:')
line_2 = getline(filename, random_number+1).strip('Answer:')
else:
line_1 = getline(filename, random_number+1).strip('Question:')
line_2 = getline(filename, random_number+2).strip('Answer:')
print(line_1)
print(line_2)
答案 2 :(得分:0)
我认为一种好的方法是使用正则表达式以及随机的 int 而不是choice()
import random
import re
all = open(filepath).readlines()
n = random.randint(0, len(all)-1)
while not re.search("^Question: ", all[n % len(all)]):
n += 1
n = n - len(all)
Question = all[n]
Answer = all[n+1]
只要所有问题都以“ Question:”开头,并且没有其他内容,我认为应该找到
答案 3 :(得分:0)
我首先要使用正则表达式将文本更改为JSON,然后加载JSON字符串以包含字典列表。从该列表的长度中选择一个随机数,然后获取答案键。
import re
import json
import random
text = """
Category: Category A
Question: Question A
Answer: Answer A
Category: Category B
Question: Question B
Answer: Answer B
Category: Category C
Question: Question C
Answer: Answer C
Category: Category D
Question: Question D
Answer: Answer D
"""
json_string = re.sub(r'(.*):\s(.*)\n(.*):\s(.*)\n(.*):\s(.*)\n?',
r'{"\1":"\2","\3":"\4","\5":"\6"},', text)
data = json.loads("[" + json_string.strip().rstrip(',') + "]")
random_item = data[random.randrange(len(data))]
question = random_item['Question']
answer = random_item['Answer']
print(question, answer, sep="\n")
输出可能是这样的:
Question C
Answer C
,并可能在下次运行中打印其他项目。