简体   繁体   中英

how to separate data from a csv file

I am working on a simple trivia game and cannot figure out a way to split up my csv file so it will randomly ask the question and then give the correct answer which would be in the same row on the csv file, separated by a comma. So there is a key and value, key has the question, value has the answer. The idea would be to display the correct answer a lot with 2 or 3 other answers for different questions which would be the wrong one. They will get a point for correctly choosing the right answer, and none for the wrong one. So far I am trying to define a function for the questions so I can randomly generate them.

def hockeyTriviaQuestions():
      fo = open("teampositionnumberplayer.csv","r")
      trivia = fo.readlines()
      for t in trivia:
          row = t.split(",")
          print(row)
      fo.close
hockeyTriviaQuestions()

with this I can see the questions with the answers but don't know how to separate them, and they also have "\\n" on some of the answers and I want to get rid of this.

Please help.

What your are doing is basically right. Post part of the input for further review.

Now, Python already has a CSV parser in the standard library. You could just use that.

To get rid of the \\n , use this:

fo = open("teampositionnumberplayer.csv","r").read().split()

This strips everything but the actual text.

Here's a pretty complete implementation:

import csv
import random
import sys

if sys.hexversion < 0x3000000:
    # Python 2.x
    inp = raw_input
    rng = xrange
    opencsvfile = lambda fname: open(fname, "rb")
else:
    # Python 3.x
    inp = input
    rng = range
    opencsvfile = lambda fname: open(fname, newline='')

NUM_ANSWERS = 4

def read_csv_file(fname):
    with opencsvfile(fname) as inf:
        incsv = csv.reader(inf)
        for row in incsv:
            yield row

def get_yn(prompt):
    while True:
        response = inp(prompt).strip().lower()
        if response in {'y','yes'}:
            return True
        elif response in {'n','no'}:
            return False

def get_int(prompt, lo=None, hi=None):
    while True:
        try:
            val = int(inp(prompt))
            if (lo is None or lo <= val) and (hi is None or val <= hi):
                return val
        except ValueError:
            pass

def play_round(qas):
    # pick some question/answer pairs at random
    questions = random.sample(qas, NUM_ANSWERS)
    # decide which question to use
    correct = random.randrange(0, NUM_ANSWERS)

    # show the question
    print("\n{}?".format(questions[correct][0]))
    # show the potential answers, numbered from 1
    for i,a in enumerate(questions, 1):
        print("{}: {}".format(i, a[1]))

    # get the user's response
    ans = get_int("Enter your answer (1-{}): ".format(NUM_ANSWERS), 1, NUM_ANSWERS)
    # was it the right answer?
    return (ans - 1 == correct)

def main():
    qas = list(read_csv_file("teampositionnumberplayer.csv"))
    win, lose = 0, 0
    while True:
        if play_round(qas):
            print("\nYou got it!")
            win += 1
        else:
            print("\nSo close... but NO!")
            lose += 1
        print("{} wins, {} losses".format(win, lose))
        if not get_yn("Play again? (y/n) "):
            break

if __name__=="__main__":
    main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM