How to display a text file as a table in Python?
本问题已经有最佳答案,请猛点这里访问。
我正在为一个根据用户输入显示设备的游戏创建一个程序。即使我已经这样做了,当它显示fixture时,它只是在一行中。这使得它看起来有点混乱,用户无法知道每个值的含义。我要做的是在表格中显示这个,标题为"夹具编号"、"播放日期"、"播放器1"、"播放器2"、"夹具是否播放?"以及"获胜的玩家"。文件示例如下:
1 2 3 | 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 |
我现在的代码是:
1 2 3 4 5 6 | fixFind = int(input("Please enter a fixture number:")) if 189 >= fixFind >= 0: f = open("fixtures.txt","r").readlines() lines = f[fixFind] print(""" Fixture:""" + lines) |
您可以使用打印字符串中的制表符(
1 2 3 4 5 6 7 8 | 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, |
输出;
1 2 | Num Date Played Time P1 P2 Played? Winner 3 07/03/17 13:00 Flip Han68 Y Han68 |
由于OP没有规定进口是不可能的,因此使用
对于文本文件
1 2 3 | 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 |
指定列:
1 | columns = ['Fixture Number', 'Date Played', 'Time Played', 'Player 1', 'Player Two', 'Was the fixture played?', 'Winning Player'] |
导入熊猫并读取无索引的文本文件,使用
1 2 3 4 5 6 7 8 | 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 |
用户输入要保留的列,并打印数据帧的子集:
1 | fixture = int(input("Please enter a fixture number:")) |
返回该设备编号的数据框子集:
1 2 3 4 5 | 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
另外一个好处是你不需要