您好,我有一個如下所示的文本文件:file '4. Can This Be Love.mp3' file '3. I Wanna Share It With You.mp3' file '8. Hold On.mp3' file '6. Playing With Fire.mp3' file '1. Take Me To The River.mp3' file '5. Giving It Up For You.mp3' file '10. Hooked On You.mp3' file '9. I Can'\''t Stop.mp3' file '7. Make It Together.mp3' file '2. Can'\''t Stop Myself.mp3' 我正在嘗試按開頭的字符串編號對文件進行排序,以便按從 1 到 10 的正確順序排列。我的代碼如下所示:#open file to readshopping = open(songInputsFilepath, "r")#get lines from filelines = shopping.readlines()#sort lineslines.sort()#close fileshopping.close()#open file for writingshoppingwrite = open(songInputsFilepath, "w")#write sorted lines to fileshoppingwrite.writelines(lines)#close file for writingshoppingwrite.close() 它幾乎可以工作,但放錯了第 10 首曲目,并導致文件排序如下:file '1. Take Me To The River.mp3' file '10. Hooked On You.mp3' file '2. Can'\''t Stop Myself.mp3' file '3. I Wanna Share It With You.mp3' file '4. Can This Be Love.mp3' file '5. Giving It Up For You.mp3' file '6. Playing With Fire.mp3' file '7. Make It Together.mp3' file '8. Hold On.mp3' file '9. I Can'\''t Stop.mp3' 有什么方法可以告訴 lines.sort() 函數使用正則表達式僅根據第一個“句點”字符之前的字符串對每一行進行排序?
1 回答

慕少森
TA貢獻2019條經驗 獲得超9個贊
如果您不介意使用正則表達式,這會起作用:
添加import re
在文件的頂部。
改變這個:
lines.sort()
對此:
lines.sort(key=lambda x: int(re.findall('\d+', x)[0]))
或者使用搜索(應該更快),正如@wjandrea 所建議的:
lines.sort(key=lambda x: int(re.search('\d+', x).group()))
您也可以通過將鍵設置為切掉第一個數字字符來完成同樣的事情,盡管它可能會稍微冗長一些。
添加回答
舉報
0/150
提交
取消