Python中的行大小(cmd)

2024-05-23 19:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的文本文件:

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) 最好的方法是这样:


Tags: oftheinforargsmoviesmovie文本文件
1条回答
网友
1楼 · 发布于 2024-05-23 19:16:00

遵循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)]))

值得注意的是,需要使用单空格字体才能获得所需的外观。你知道吗

相关问题 更多 >