简体   繁体   English

在Python中对文本文件的内容进行排序和对齐

[英]Sorting and aligning the contents of a text file in Python

In my program I have a text file that I read from and write to. 在我的程序中,我有一个读取和写入的文本文件。 However, I would like to display the contents of the text file in an aligned and sorted manner. 但是,我想以对齐和排序的方式显示文本文件的内容。 The contents currently read: 当前内容为:

Emily, 6
Sarah, 4
Jess, 7

This is my code where the text file in read and printed: 这是我的代码,其中读取并打印了文本文件:

elif userCommand == 'V':
    print "High Scores:"
    scoresFile = open("scores1.txt", 'r')
    scores = scoresFile.read().split("\n")
    for score in scores:
        print score
    scoresFile.close()

Would I have to convert this information into lists in order to be able to do this? 我是否必须将此信息转换为列表才能执行此操作? If so, how do I go about doing this? 如果是这样,我该怎么做?

When writing to the file, I have added a '\\n' character to the end, as each record should be printed on a new line. 写入文件时,我在末尾添加了一个'\\ n'字符,因为每条记录应打印在新行上。

Thank you 谢谢

You could use csv module, and then could use sorted to sort. 您可以使用csv模块,然后可以使用sorted进行排序。

Let's says, scores1.txt have following 假设,scores1.txt有以下内容

Richard,100
Michael,200
Ricky,150
Chaung,100

Test 测试

import csv

reader=csv.reader(open("scores1.txt"),dialect='excel')
items=sorted(reader)
for x in items:
    print x[0],x[1]

...
Emily  6
Jess  7
Sarah  4

Looks like nobody's answered the "aligned" part of your request. 似乎没有人回答您请求的“对齐”部分。 Also, it's not clear whether you want the results sorted alphabetically by name, or rather by score. 另外,不清楚是否要按名称或分数对字母进行排序。 In the first case, alphabetical order (assuming Python 2.6): 在第一种情况下,按字母顺序排列(假设Python 2.6):

with open("scores1.txt", 'r') as scoresFile:
  names_scores = [[x.strip() for x in l.split(',', 1)] for l in scoresFile]
# compute column widths
name_width = max(len(name) for name, score in names_scores)
score_width = max(len(score) for name, score in names_scores)
# sort and print
names_scores.sort()
for name, score in names_scores:
  print "%*s %*s" % (name_width, name, score_width, score)

If you want descending order by score, just change the names_scores.sort() line to two: 如果names_scores.sort()分数降序,只需将names_scores.sort()行更改为两个即可:

def getscore_int(name_score): return int(name_score[1])
names_scores.sort(key=getscore_int, reverse=True)
  1. to sort stuff in Python, you can use sort()/sorted() . 要对Python中的内容进行排序,可以使用sort()/ sorted()
  2. to print, you can use print with format specifiers, str.rjust/str.ljust, pprint etc 要进行打印,您可以将print与格式说明符,str.rjust / str.ljust,pprint等一起使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM