【问题标题】:Problems while sorting alphabeticaly a .txt file (one line was dropped)?按字母顺序排序 .txt 文件时出现问题(删除了一行)?
【发布时间】:2015-05-01 10:51:51
【问题描述】:

我需要按字母顺序对包含 id 和内容列的 .txt 文件进行排序,如下所示:

SSADDS__234_234dvefeSADF, 1
SSFDS2342_234_dfsk___wewrew, 2
....
DFGFG__sasd_DFSD23423_3232, 3

然后我做以下排序:

f=open(raw_input("give me the file"))
for word in f:
    l = sorted(map(str.strip, f))
    #print "\n",l
    a = open(r'path', 'w')
    #a.writelines(l)
    a.write('\n'.join(l)+'\n')

该文件包含 500 行(id 和内容)。问题在于,当我运行上述脚本时,我得到 499 而不是 500,为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • 为什么要在 for 循环中排序?另外,你得到索引 499,例如。 f[499] 或者你得到长度 499,len(f) == 499?
  • 因为这是我解决这个问题的最佳方法......关于如何排序 alfabeticaly 这个的任何其他想法?感谢您的反馈!

标签: python python-2.7 sorting io


【解决方案1】:

只需消除 for 循环,您就可以开始了:

from string import strip

with open(raw_input("give me the file")) as f:
    lines = sorted(map(strip, f))

    with open(r'path', 'w') as a:
        a.write('\n'.join(lines))

【讨论】:

    【解决方案2】:

    您的问题出在 for 循环中。只需删除 for 循环并运行您的程序,无需任何其他更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2020-02-11
      相关资源
      最近更新 更多