python如何显示文本信息_如何在python中将文本文件显示为表?

本问题已经有最佳答案,请猛点这里访问。

我正在为一个根据用户输入显示设备的游戏创建一个程序。即使我已经这样做了,当它显示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声明。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值