2014-02-28 29 views
0

我正在研究一個簡單的瑣事遊戲,並且無法找出分割我的csv文件的方法,因此它會隨機提出問題,然後給出相同的正確答案在csv文件中用逗號分隔。所以有一個關鍵和價值,關鍵有問題,價值有答案。這個想法應該是針對不同的問題顯示正確的答案,其中有2個或3個其他答案,這是錯誤的。他們會得到正確選擇正確答案的一個觀點,而沒有錯誤的答案。到目前爲止,我正在嘗試爲問題定義一個函數,以便隨機生成它們。如何從csv文件中分離數據

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

這個我可以看到答案的問題,但不知道如何把它們分開,它們也有「\ n」在一些問題的答案,我想擺脫這一點。

請幫忙。

回答

0

爲了擺脫\n的,使用此:

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

這條一切,但實際文本。

+0

我試圖把這個和... – user3349243

+0

嗯... Python版本是您使用了錯誤?如果您不知道,請在您的shell中鍵入python -V。 –

+0

我相信蟒蛇3 – user3349243

1

你在做什麼基本上是正確的。發佈部分輸入以供進一步審覈。

現在,Python已經在標準庫中有一個CSV parser。你可以使用它。

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