如何从csv文件中分离数据

时间:2014-02-28 01:31:27

标签: python function csv split

我正在开发一个简单的琐事游戏,无法想出一种方法来拆分我的csv文件,所以它会随机提出问题,然后给出正确的答案,这些答案将在csv文件的同一行中,由一个逗号。所以有一个关键和价值,关键有问题,价值有答案。我的想法是用2或3个其他答案显示正确的答案,以解决不同的问题。他们会得到正确选择正确答案的一点,而对于错误答案则没有。到目前为止,我正在尝试为问题定义一个函数,以便我可以随机生成它们。

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

有了这个,我可以看到问题的答案,但不知道如何分开它们,他们也有一些答案的“\ n”,我想摆脱这个。

请帮忙。

3 个答案:

答案 0 :(得分:1)

你在做什么基本上是正确的。发布部分输入以供进一步审核。

现在,Python在标准库中已经有CSV parser了。你可以使用它。

答案 1 :(得分:0)

要摆脱\n,请使用:

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

这除了实际文本之外的所有内容。

答案 2 :(得分:0)

这是一个非常完整的实现:

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()