Turning a text file into a tabular format
我在尝试正确格式化文本文件以适合学校项目所需的标准时遇到问题。我已经坚持了一段时间,对编码还是很陌生,想知道是否有人可以理解和实现答案,希望可以从经验丰富的人那里学习。
我想转换一个文本文件,该文件可以由用户在文件内输入如下形式:
1 2 3 4 | Lennon 12 3.33 McCartney 57 7 Harrison 11 9.1 Starr 3 4.13 |
并创建它以适合如下表格格式:
1 2 3 4 | Name Hours Total Pay Lambert 34 357.00 Osborne 22 137.50 Giacometti 5 503.50 |
我可以创建标题,尽管它可能不是漂亮的代码,但是当我打印测试文件的内容时,通常结果如下:
1 2 3 4 5 | Name Hour Total pay Lennon 12 3.33 McCartney 57 7 Harrison 11 9.1 Starr 3 4.13 |
而且我不知道如何正确格式化它,使其看起来像是正确的表,并且正确地符合实际的标题,我不确定如何真正解决它,或者甚至从哪里开始,因为我还没有做过任何真正的依据。
在尝试使用
)
1 2 3 4 5 6 7 8 | file_name = input("Enter the file name:") print("Name" +"" * 12 +"Hour" +"" * 6 +"Total pay") with open(file_name, 'r') as f: for line in f: print(line, end='') |
我知道它看起来很简单,因为事实如此。我们的讲师希望我们使用"打开"命令,并尝试远离可能使其可读性较差但仍尽可能紧凑的内容。这包括导入第三方工具,这些工具减少了使用Beautifultable之类的东西的机会,就像其他一些朋友提供的那样,这是更轻松的出路。
我有一个同学说要阅读将其变成列表的行,并从那里进行某种格式的调整,而另一个同学说我可以在不列出的情况下格式化它。尽管我发现如果将换行符" n"转换为列表,它会出现在每个列表索引的末尾
例如:
', 'McCartney 57 7
', 'Harrison 11 9.1
', 'Starr 3 4.13']
尽管我不了解如何格式化列表中的内容,以便可以将名称与每个数字变量分开并与标头保持一致,因为我对for循环没有太多的经验如果我对此轻描淡写,说可以在班上轻松解决。
我并不是在寻找直接的编码答案,而是在正确的方向或在哪里可以读到如何操纵列出的内容的问题
这可以使您朝正确的方向前进:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | data_filename = 'employees.txt' headers = 'Name', 'Hours', 'Rate' # Column names. # Read the data from file into a list-of-lists table. with open(data_filename) as file: datatable = [line.split() for line in file.read().splitlines()] # Find the longest data value or header to be printed in each column. widths = [max(len(value) for value in col) for col in zip(*(datatable + [headers]))] # Print heading followed by the data in datatable. # (Uses '>' to right-justify the data in some columns.) format_spec = '{:{widths[0]}} {:>{widths[1]}} {:>{widths[2]}}' print(format_spec.format(*headers, widths=widths)) for fields in datatable: print(format_spec.format(*fields, widths=widths)) |
输出:
1 2 3 4 5 | Name Hours Rate Lennon 12 3.33 McCartney 57 7 Harrison 11 9.1 Starr 3 4.13 |
您可以为此使用熊猫,数据框将完成所需的工作
1 2 3 4 | import pandas as pd df = pd.read_csv('file.txt', sep='\s{1,}') df.columns = ['Name','Hours','Total Pay'] print(df) |
希望这可以帮助。