您好,我有一個(gè)如下所示的文本文件: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' 我正在嘗試按開(kāi)頭的字符串編號(hào)對(duì)文件進(jìn)行排序,以便按從 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() 它幾乎可以工作,但放錯(cuò)了第 10 首曲目,并導(dǎo)致文件排序如下: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() 函數(shù)使用正則表達(dá)式僅根據(jù)第一個(gè)“句點(diǎn)”字符之前的字符串對(duì)每一行進(jìn)行排序?
1 回答

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