在Python中排序列表时忽略引号?

时间:2014-03-25 05:07:42

标签: sorting python-3.x jquery-ui-sortable sorted sortedlist

我正在创建一个程序来读取文件,按字母顺序排列信息,然后将其粘贴到输出中。我遇到的唯一问题是以引号(“”)开头的信息。

该程序的主要功能是自动排序MLA作品引用页面(显然很有趣)。

这是代码......我会喜欢任何批评,建议和意见(请记住这是我的第一个正常运作的程序)

TL; DR - 如何忽略“并且仍然根据下一个字符按字母顺序排列数据..

代码:

import os, sys

#List for text
mainlist = []
manlist = []

#Definitions
def fileread():
  with open("input.txt", "r+") as f:
    for newline in f:
      str = newline.replace('\n', '')
      #print(str)
      manlist.append(str)
  mansort(manlist)
  #print("Debug")
  #print(manlist)

def main():
  print("Input Data(Type 'Done' When Complete or Type 'Manual' For file-read):")
  x = input()
  if x.lower() == 'done':
    sort(mainlist)
  elif x == '':
    print("You must type something!")
    main()
  elif x.lower() == 'manual':
    fileread()
  else:
    mainlist.append(x)
    main()


def mansort(manlist):
  print("What would you like to name the file?(Exit to Terminate):") 
  filename = input()
  manlist = sorted(manlist, key=str.lower)
  for s in manlist:
    finalstring2 = '\n'.join(str(manlist) for manlist in manlist)
  if filename == '':
    print("You must choose a name!")
  elif filename.lower() == 'exit':
sys.exit()
  else:
    with open(filename + ".txt", "w+") as f:
      f.write(str(finalstring2))


def sort(mainlist):
  os.system("cls")
  mainlist = sorted(mainlist, key=str.lower)
  for s in mainlist:
    finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
  print(finalstring)

  print("What would you like to name the file?(Exit to Terminate):") 
  filename = input()

  if filename.lower() == 'exit':
    sys.exit()
  elif  filename == '':
    print("You must type something!")
    sort(mainlist)
  else:
    with open(filename + ".txt", "w+") as f:
      f.write(str(finalstring))

  print("\nPress Enter To Terminate.")
  c = input()


main()


#Clears to prevent spam.
os.system("cls")

请保持所有的批评建设性......另外,作为一个例子,我希望“beta”在alpha之后出现,但是对于我当前的程序,它将首先归结于“”的

1 个答案:

答案 0 :(得分:1)

sorted(mainlist, key=str.lower)

您已经发现可以对mainlist上的每个项目进行一些转换,并按照#34;映射"进行排序。值。此技术有时称为Schwartzian Transform

更进一步 - 删除引号将其转换为小写。

sorted(mainlist, key=lambda s: s.strip('"').lower())