2017-05-06 52 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声明。

相关问题