簡體   English   中英

使用python按數字順序對具有int和string值的文件進行排序

[英]Sort thru a file with int and string values in numerical order with python

我有一個具有以下值的文本文件:

username:password - number of daily visits: 15
username:password - number of daily visits: 482
username:password - number of daily visits: 4823

我想按從最高到最低的數字順序過濾文件,因此訪問次數最多的將位於文件的頂部,而最低的位於文件的末尾,我想這樣做但保留所有字符串值,所以它看起來像這樣:

username:password - number of daily visits: 4823
username:password - number of daily visits: 482
username:password - number of daily visits: 15

我設法做到了,但字符串值不會被維護,所以它只是:

4823
482
15

我真的不知道,我是初學者還在學習。

假設您總是在行尾有一個數字,您可以使用sorted和自定義鍵:

with open('file.txt') as f, open('file2.txt', 'w') as f2:
    f2.writelines(sorted(f.readlines(),
                         key=lambda s: int(s.rsplit(' ')[-1].strip()),
                         reverse=True))

輸入file.txt

username:password - number of daily visits: 15
username:password - number of daily visits: 482
username:password - number of daily visits: 4823

輸出file2.txt

username:password - number of daily visits: 4823
username:password - number of daily visits: 482
username:password - number of daily visits: 15

這個怎么運作

  • 讀取文件內容作為行列表: f.readlines()
  • 通過拆分最后一個空格上的行,獲取最后一項( [-1] ),確保沒有尾隨換行符( strip() )並轉換為 int 來提取列表數字。
  • 使用 sorted 對行進行sorted ,使用上面提取的數字作為鍵,使用相反的順序首先獲得更大的數字
  • writelines在新文件中寫入行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM