目标:根据最后一个斜杠之后出现的字符按字母顺序对文本文件进行排序。请注意,最后一个斜杠之前有随机数字。
文本文件的内容:
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()
代码不起作用。
最佳答案
我会将不同的 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)
参见here了解关键功能的更详细说明。
关于python - 如何在字符的最后一个实例之后对文本文件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72178137/