如何按字母顺序对文本文件排序,同时保留行距

2024-06-01 02:05:39 发布

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

我有以下代码:

test=open("NewTextDocument.txt", "r")
lines1 = (test.readlines())
lines1.sort()
print(lines1)`

我用它来存储一个包含以下内容的文本文件:

('lars', ' in class', '1', ' has got a score of', 8)
('lars2', ' in class', '1', ' has got a score of', 1)
('as', ' in class', '1', ' has got a score of', 1)
('12', ' in class', '1', ' has got a score of', 0)
('lars', ' in class', '1', ' has got a score of', 8)
('lars', ' in class', '1', ' has got a score of', 8)
('lars', ' in class', '1', ' has got a score of', 7, ' with a time of', 39.79597997665405)
('test', ' in class', '1', ' has got a score of', 1, ' with a time of', 17)

我要做的是按字母顺序对文件中的行进行排序,同时保留换行符。例如:

('as', ' in class', '1', ' has got a score of', 1)
('lars', ' in class', '1', ' has got a score of', 8)
('lars2', ' in class', '1', ' has got a score of', 1)

但是,运行代码后得到的结果是:

["('12', ' in class', '1', ' has got a score of', 0)\n", 
"('as', ' in class', '1', ' has got a score of', 1)\n", 
"('lars', ' in class', '1', ' has got a score of', 7, ' with a time of', 39.79597997665405)\n", 
"('lars', ' in class', '1', ' has got a score of', 8)\n", 
"('lars', ' in class', '1', ' has got a score of', 8)\n", 
"('lars', ' in class', '1', ' has got a score of', 8)\n", 
"('lars2', ' in class', '1', ' has got a score of', 1)\n", 
"('test', ' in class', '1', ' has got a score of', 1, ' with a time of', 17)"]

我怎样才能解决这个问题?你知道吗


Tags: of代码intesttimeaswithopen
2条回答

你所犯的错误就是打印一个没有任何格式的列表。打印行1只会弹出一个包含该列表所有内容的长行。您要循环浏览列表并一次打印一行:

for line in lines1:
    print line,

我添加了逗号,因为您的所有行都以换行符结尾,所以用逗号结尾打印意味着它不会每次都添加额外的换行符。你知道吗

再加上

for line in lines1:
    print line 

完整的代码将变成

>>> with open("results.txt") as test:
...     lines = test.readlines()
...     lines.sort()
...     for i in lines:
...             print i

输出

('12', ' in class', '1', ' has got a score of', 0)

('as', ' in class', '1', ' has got a score of', 1)

('lars', ' in class', '1', ' has got a score of', 7, ' with a time of', 39.79597997665405)

('lars', ' in class', '1', ' has got a score of', 8)

('lars', ' in class', '1', ' has got a score of', 8)

('lars', ' in class', '1', ' has got a score of', 8)

('lars2', ' in class', '1', ' has got a score of', 1)

('test', ' in class', '1', ' has got a score of', 1, ' with a time of', 17)

相关问题 更多 >