目標:根據出現在最后一個斜線之后的字符按字母順序對文本檔案進行排序。請注意,在最后一個斜線之前有亂數。
文本檔案的內容:
https://www.website.com/1939332/delta.html
https://www.website.com/2237243/alpha.html
https://www.website.com/1242174/zeta.html
https://www.website.com/1839352/charlie.html
期望的輸出:
https://www.website.com/2237243/alpha.html
https://www.website.com/1839352/charlie.html
https://www.website.com/1939332/delta.html
https://www.website.com/1242174/zeta.html
代碼嘗試:
i = 0
for line in open("test.txt").readlines(): #reading text file
List = line.rsplit('/', 1) #splits by final slash and gives me 4 lists
dct = {list[i]:list[i 1]} #tried to use a dictionary
sorted_dict=sorted(dct.items()) #sort the dictionary
textfile = open("test.txt", "w")
for element in sorted_dict:
textfile.write(element "\n")
textfile.close()
代碼不起作用。
uj5u.com熱心網友回復:
我會向該函式傳遞一個不同key的sorted函式。例如:
with open('test.txt', 'r') as f:
lines = f.readlines()
lines = sorted(lines, key=lambda line: line.split('/')[-1])
with open('test.txt', 'w') as f:
f.writelines(lines)
有關關鍵功能的更詳細說明,請參見此處。
uj5u.com熱心網友回復:
在你運行它之前,我假設你在 test.txt 的末尾有一個換行符。這將修復“結合第二行和第三行”。
如果你真的想使用字典:
dct = {}
i=0
with open("test.txt") as textfile:
for line in textfile.readlines():
mylist = line.rsplit('/',1)
dct[mylist[i]] = mylist[i 1]
sorted_dict=sorted(dct.items(), key=lambda item: item[1])
with open("test.txt", "w") as textfile:
for element in sorted_dict:
textfile.write(element[i] '/' element[i 1])
你做錯了什么
在第一行,你命名你的變數List,在第二行你使用list.
List = line.rsplit('/', 1)
dct = {list[i]:list[i 1]}
變數名區分大小寫,因此您每次都需要使用相同的大小寫。此外,Python 已經有一個內置list類。它可以被覆寫,但我不建議將變數命名為list,dict等。
(list[i]實際上只會生成一個types.GenericAlias物件,它是一個型別提示,與串列完全不同,根本不是你想要的。)
你還寫了
dct = {list[i]:list[i 1]}
它在每次回圈迭代中重復創建一個新字典,覆寫dct之前存盤的任何內容。相反,您應該在回圈之前創建一個空字典,并在每次要更新它時為其鍵分配值,就像我所做的那樣。
您sort在回圈中的每次迭代中呼叫;你應該只在回圈完成后呼叫一次。畢竟,您只想對字典進行一次排序。
您還open兩次打開檔案,雖然最后關閉它,但我建議使用背景關系管理器和with我所做的陳述句,以便自動處理檔案關閉。
我的代碼
sorted(dct.items(), key=lambda item: item[1])
表示該sorted()函式使用item元組(字典項)中的第二個元素作為排序的“度量”。
`textfile.write(element[i] '/' element[i 1])`
是必要的,因為當您這樣做時rsplit('/',1),您洗掉了/資料中的 s;您需要將它們添加回來并從element元組中重建字串write。
你不需要 \nintextfile.write因為readlines()保留了\n. 這就是為什么你應該用換行符結束文本檔案:這樣你就不必區別對待最后一行。
uj5u.com熱心網友回復:
def sortFiles(item):
return item.split("/")[-1]
FILENAME = "test.txt"
contents = [line for line in open(FILENAME, "r").readlines() if line.strip()]
contents.sort(key=sortFiles)
with open(FILENAME, "w") as outfile:
outfile.writelines(contents)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471957.html
標籤:Python python-3.x 列表 字典
