本问题已经有最佳答案,请猛点这里访问。
我正在为一个根据用户输入显示设备的游戏创建一个程序。即使我已经这样做了,当它显示fixture时,它只是在一行中。这使得它看起来有点混乱,用户无法知道每个值的含义。我要做的是在表格中显示这个,标题为"夹具编号"、"播放日期"、"播放器1"、"播放器2"、"夹具是否播放?"以及"获胜的玩家"。文件示例如下:
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)
你能从你的文本文件中提供一些样本数据吗?
您可以参考以下答案:stackoverflow.com/a/15344226/6556102
@Kyle341嘿,伙计,既然你没有说过你不能导入模块,我已经用流行的pandas模块给了你一个答案。它将文件转换为数据帧,然后打印输出。你不必乱摆弄格式。让我知道你的想法:)
您可以使用打印字符串中的制表符(\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
由于OP没有规定进口是不可能的,因此使用read_csv的pandas更容易做到这一点。
对于文本文件'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声明。