2017-05-06 54 views
1

我正在創建一個遊戲程序,根據用戶輸入顯示裝置。儘管我已經完成了這個工作,但是當它顯示夾具時,它只是在一行中。這導致它看起來有點混亂,用戶無法知道每個值的含義。我想要做的就是在一個表格中顯示這個標題'燈號','播放日期','播放器1','播放器2','播放器是否播放?和'贏球員'。該文件的樣本是:如何在Python中將文本文件顯示爲表格?

1,05/03/17,13:00,DarrenL,Philippa93,Y,DarrenL 
2,06/03/17,13:00,TommyBoy,Paul4,Y,Paul4 
3,07/03/17,13:00,Flip,Han68,Y,Han68 

我現在所擁有的代碼是:

fixFind = int(input("Please enter a fixture number: ")) 
if 189 >= fixFind >= 0: 
    f = open("fixtures.txt", "r").readlines() 
    lines = f[fixFind] 
    print(""" 
    Fixture: """ + lines) 
+0

你能提供一些來自你的文本文件的示例數據嗎? – Chuck

+0

你可能想要參考這個答案:http://stackoverflow.com/a/15344226/6556102 – jedruniu

+0

@ Kyle341嘿,因爲你還沒有說你不能導入模塊,我給你一個答案使用流行的「熊貓」模塊。它將您的文件轉換爲數據幀,然後打印輸出。您不必亂用格式。讓我知道你的想法 :) – Chuck

回答

1

您可以在打印字符串中使用的標籤(在\t序列)作爲這樣的一個簡單的方法。但是,您必須注意列長度並在每行上超過80個字符以保持輸出正確排列。

fixFind = int(input("Please enter a fixture number: ")) 

print "Num\tDate Played\tTime\tP1\tP2\tPlayed?\tWinner" 
if 189 >= fixFind >= 0: 
    f = open("fixtures.txt", "r").readlines() 
    lines = f[fixFind] 
    for i in lines.split(","): 
    print '%s\t' % i, 

輸出;

Num Date Played Time P1  P2  Played? Winner 
3 07/03/17 13:00 Flip Han68 Y  Han68 
0

由於OP未指定的進口都沒有更多鈔票,以pandas更容易做到這一點使用read_csv

對於文本文件'fixtures'

1,05/03/17,13:00,DarrenL,Philippa93,Y,DarrenL 
2,06/03/17,13:00,TommyBoy,Paul4,Y,Paul4 
3,07/03/17,13:00,Flip,Han68,Y,Han68 

指定列:

columns = ['Fixture Number', 'Date Played', 'Time Played', 'Player 1', 'Player Two', 'Was the fixture played?', 'Winning Player'] 

進口熊貓和閱讀的文本文件,沒有索引,使用columns列名:

import pandas as pd 
df = pd.read_csv("fixtures.txt", index_col=False, names=columns) 

>> 
    Fixture Number Date Played Time Played Player 1 Player Two Was the fixture played? Winning Player 
0    1 05/03/17  13:00 DarrenL Philippa93      Y  DarrenL 
1    2 06/03/17  13:00 TommyBoy  Paul4      Y   Paul4 
2    3 07/03/17  13:00  Flip  Han68      Y   Han68 

用戶輸入其列,以保持和數據幀的打印子集:對於該夾具數據幀的

fixture = int(input("Please enter a fixture number: ")) 

返回子集:

print df[df['Fixture Number'] == fixture] 

>> 
    Fixture Number Date Played Time Played Player 1 Player Two Was the fixture played? Winning Player 
0    1 05/03/17  13:00 DarrenL Philippa93      Y  DarrenL 

文檔瀏覽:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

增加的好處是您不需要if聲明。

相關問題