如何将CSV文件解析为字典并一一使用(不使用CSV库)

时间:2019-06-12 17:21:36

标签: python-3.x csv

我有一项家庭作业,本质上要求您解析一个CSV文件(最好不使用CSV库,但实际上最简单的方法是可以的),并将其内容移动到字典中,然后从该字典中打印某些部分并使用其他部分部分作为答案。

我尝试过这种方法:

with open('questions.txt') as f:
  questions={}
  for line in f:
    csvvalues = line.split(',')
    csvvalues = [x.rstrip() for x in csvvalues]
    questions[csvvalues[-1]] = {
      'Q' : csvvalues[0],
      'A' : csvvalues[1:len(csvvalues)-1]
    }

  print(questions)

但是格式很奇怪而且无法使用。

这是我到目前为止的代码:

quiz={}
f=open("questions.txt","r")
for line in f:
     parts=line.split(",")
     quiz[parts[0]]=[parts[1],parts[2],parts[3],parts[4].strip("\n")]
for i in range(10): 
     print(quiz)
     ans=input("Input your answer")
     if ans==quiz[parts[5]]:
          print("Correct!")
     else:
          print("Nope, the answer is")
f.close()

但是它带有一个KeyError,并且两个问题(有关上下文,请参阅我的文件)同时出现,我不希望-它们应该一次出现。

预期结果:

Which birthstone is associated with the month of May? Diamond, Ruby, Emerald, Sapphire 
Input your answer <user inputs answer>
Correct! (or)
Nope, the right answer is (correct answer as A B C or D)
(then next question is outputted)

我的CSV文件:(“问题”)

Which birthstone is associated with the month of May?,Diamond,Ruby,Emerald,Sapphire,C
Which two colours as on the flag of Poland?,Red and Green, Blue and White, Green and White, Red and White,D

1 个答案:

答案 0 :(得分:-1)

如果您真的不想使用第三方库:

def parse_csv(file_name: str) -> dict:
    retval = {}
    with open(file_name) as f:
        for line in f:
            data = line.strip().split(',')
            key, *values = (v.strip() for v in data)
            retval[key] = values
    return retval

questions = parse_csv('questions.txt')
for question, answers in questions.items():
    correct = answers[-1]
    answers = answers[:-1]

    result = input(f"{question}: {','.join(answers)}")

    if result == correct:
        print('Yeah, mate!')
    else:
        print(f'The correct answer is {correct!r}')