没有错误,但是当我尝试打印随机项时,它每次只会打印.txt文件的最后一项。
如何将文本文件转换为列表?更具体地说,如何将.split的整个左侧转换为列表?
欢迎您提出任何见解!
我的.txt文件的格式是这样的。
Marunong ka bang mag-Ingles?你知道怎么说英语吗?
5月电话吗?这边有电话吗?
import hashlib
import random
testFile = ""
def qSearch():
options = input ("Vocab/Grammar/or Special? (v/g/s)")
if options == "v":
testFile = "Vocabtest"
Vocab()
elif options == "g":
Grammar()
testFile = "Grammartest"
elif options == "s":
Special()
testFile = "Specialtest"
else:
qSearch()
def Vocab():
with open('Vocabtest.txt','r') as f:
for line in f:
questions, answers = line.split("=")
print (random.choice([questions]))
qSearch()
(在终端返回)
Vocab / Grammar /或Special? (V / G / S)V
5月电话吗?
答案 0 :(得分:0)
您的Vocab()
函数正在读取所有数据,但不能以任何重要或有用的方式保存该数据。在下面的修订代码中,我们将所有问题/答案对存储到字典中。
将数据放入字典允许我们在字典中查询密钥以获得配对值。
在随机选择密钥之前(使用random.choice
,我们会将dict.keys()对象转换为可索引的列表。
def Vocab():
with open('Vocabtest.txt','r') as f:
q_and_a = dict() # creates a dictionary
for line in f:
question, answer = line.split("=")
q_and_a[question] = answer # stores the question and answer
keys = list(q_and_a.keys()) # create a list of keys
print(q_and_a[random.choice(keys)]) # randomly selects a key
# (question) and uses it to get
# an answer.