【发布时间】:2015-12-30 17:19:32
【问题描述】:
我的文本文件中有一个数据,其中包含“Test DATA_g004, Test DATA_g003, Test DATA_g001, Test DATA_g002”。
是否可以在不使用“Test DATA_”字样的情况下对其进行排序,以便将数据排序为 g001、g002、g003 等?
我尝试了.split("Test DATA_") 方法,但它不起作用。
def readFile():
#try block will execute if the text file is found
try:
fileName = open("test.txt",'r')
data = fileName.read().split("\n")
data.sort (key=alphaNum_Key) #alternative sort function
print(data)
#catch block will execute if no text file is found
except IOError:
print("Error: File do not exist")
return
#Human sorting
def alphaNum(text):
return int(text) if text.isdigit() else text
#Human sorting
def alphaNum_Key(text):
return [ alphaNum(c) for c in re.split('(\d+)', text) ]
【问题讨论】:
标签: python string sorting file-io