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

时间:2015-05-12 09:36:21

标签: python sorting

我有以下代码:

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)"]

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

你所做的就是打印没有任何格式的列表。打印lines1将只用该列表的所有内容吐出一条长行。您想循环遍历列表并一次打印一行:

lst = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
result = []

for element in lst:
  is_prefixed = False
  for possible_prefix in lst:
    if element is not possible_prefix and element.startswith(possible_prefix):
      is_prefixed = True
      break
  if not is_prefixed:
    result.append(element)

我添加了逗号,因为所有行都以换行符结尾,因此使用尾随逗号进行打印意味着每次都不会添加额外的换行符。

答案 1 :(得分:0)

添加,

end

完整代码将成为

for line in lines1:
    print line 

输出

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