如何将.txt文件的内容转换为列表并打印该列表中的随机项

时间:2017-12-28 22:27:32

标签: python list

没有错误,但是当我尝试打印随机项时,它每次只会打印.txt文件的最后一项。

如何将文本文件转换为列表?更具体地说,如何将.split的整个左侧转换为列表?

欢迎您提出任何见解!

我的.txt文件的格式是这样的。

Ano Iyan?那是什么

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月电话吗?

1 个答案:

答案 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.