Python中的行大小(cmd)

问题描述 投票:2回答:1

我有这样的文本文件:

A fistful of Dolars|Western|100|Sergio Leone|Clint Eastwood|Italia|1964
For a few dolars more|Western|130|Sergio Leone|Clint Eastwood|Italia|1965
The Good, the Bad and the Ugly|Western|179|Sergio Leone|Clint Eastwood|Italia|1966

我尝试以这种方式格式化:

def movie_list():
    movies = open('movies.txt','r').readlines()
    for i in movies:
        movie = i.strip("\n").split("|")
        for args in (('Name','Genre','Running time', 'Director', 'Starring', 'Country', 'Released'),(movie[0], movie[1], movie[2], movie[3], movie[4], movie[5], movie[6]+"\n")):
            print (('{0:<13} {1:<10} {2:<10} {3:<13} {4:<13} {5:<8} {6:<4}').format(*args))

并且几乎没有类似的方式......

如何根据文本文件中每行的字符串长度设置行的大小(即电影)

(我在油漆中做到了:D)最好的方法是看起来像这样:

python text formatting tabular
1个回答
0
投票

遵循stackoverflow.com/a/12065663/8881141中概述的方法很好地工作:

movies = []

with open('movies.txt', 'r') as f:
    for line in f:
        movies.append(line.strip('\n').split('|'))

f.close()

widths = [max(map(len, col)) for col in zip(*movies)]

for movie in movies:
    print('   '.join([col.ljust(val) for col, val in zip(movie, widths)]))

值得注意的是,需要等宽字体才能获得所需的外观。

© www.soinside.com 2019 - 2024. All rights reserved.