2013-02-21 103 views
0

我是初學者。我想編寫一個腳本來從其文件夾中清理舊的Google Chrome應用程序版本,我想知道如何以有效的方式「排序」應用程序版本號。什麼是最好的方法來做到這一點?排序應用程序版本號

這裏我的 「春季大掃除」 腳本:

import os 
import sys 
import re 
import operator 
import shutil 


GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY=r'C:\Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\Application' 

REGEX_GOOGLE_CHROME_APPLICATION_VERSION = '^(\d+)\.(\d+)\.(\d+)\.(\d+)$' 


def sorted_by_version_number(versions_list): 
    version_elements = len(versions_list[0]) 
    for index in range(version_elements-1, 0, -1): 
    key = operator.itemgetter(index) 
    versions_list.sort(key=key, reverse = True) 
    return versions_list 


def delete_old_google_chrome_versions(): 
    REGEX = re.compile(REGEX_GOOGLE_CHROME_APPLICATION_VERSION) 
    application_versions = [] 
    for filename in os.listdir(GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY): 
    filepath = os.path.join(GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY, 
          filename) 
    if os.path.isdir(filepath): 
     match = REGEX.match(filename) 
     if match: 
     version = (v1, v2, v3, v4) = [int(match.group(i)) for i in range(1, 5)] 
     application_versions.append(version) 
    versions_to_delete = sorted_by_version_number(application_versions)[1:] 
    for application_version in versions_to_delete: 
    directory_name = '.'.join([str(v) for v in application_version]) 
    directory_path = os.path.join(GOOGLE_CHROME_APPLICATION_VERSIONS_DIRECTORY, 
            directory_name) 
    print('Deleting Google Chrome application directory: {}...'.format(
     directory_path)) 
    # shutil.rmtree(directory_path) 


def main(): 
    delete_old_google_chrome_versions() 


if __name__ == '__main__': 
    main() 

可選的,怎麼會這樣腳本加以改進?任何建議都會有幫助,因爲我在Python中毫無用處。

回答

0

我回答這個問題直接轉換成Python:

How to compare software version number using js? (only number)

您可以使用此比較算法對列表進行排序。

+0

我的直覺是我將穩定的虛線字符串值從最不重要到最重要的值視爲int值,比作爲典型「集合」的輔助方法多次運行「Comparator」函數更有效率排序? (例如某些類型的Quicksort,其他類型的Mergesort等) – Robottinosino 2013-02-21 13:37:55

+0

如果您知道該號碼有多少部分,則可以將它們轉換爲可比較的值。但是除非你做了成千上萬的事情,否則這一切都沒有太大的影響。計算機是爲計算事物而製造的! – Joe 2013-02-21 13:54:44

+0

我是一名只接受高中教育的初學者。我將計算機科學作爲一種業餘愛好,我永遠不會找到工作。既然這是爲了好玩,我想學會做對。我真的不喜歡這樣的想法:「如果我可以鍛鍊我的大腦並在那裏找到解決方案,或者從其他用戶那裏學習,只是因爲計算機可以做浪費的計算。」「快」:) – Robottinosino 2013-02-21 13:59:22