2016-03-30 29 views
0

我是新來編碼和工作在文件檢查程序的早期階段。 我正在編寫一個程序,以查看文件是否在其標題中包含「正確信息」。驗證文件名的一部分存在於字典或列表中,Python 2.7

我目前被困在如何檢查標題中的part是否與字典或列表中的可接受名稱匹配。

我的代碼如下。如果我放入的標題包含少於3個部分,則會引發錯誤。但是,如果我使用3 parts作爲標題,即使parts沒有與列表或字典中的任何內容匹配,我的程序都會聲明標題是正確的(不是)。

我知道if-statements是因爲所有的或者是粗糙的,但這是我現在最好的想法,而不是每個part寫一大堆if-statements

任何人都可以幫我糾正代碼,以便我可以根據列表或字典檢查部分標題以確保部分存在於列表/字典中嗎?

一個例子(正確)的文件名應該是:DJ_BR_UVT.xls 和不正確的文件名的例子是:DJ_BR_staford.xls *作爲一個側面說明,parts或物種,學校,縮寫,可以在任何順序文件名。

def checkFilename(filename): 
    print 'filename = ' + filename 
    Parts = filename.split('_') 
if len(Parts) != 3: 
    print "There are " + str(len(Parts)) + " that is an incorrect amount of info in file name. There should be 3 parts to your file name" 
    return 

Part1 = Parts[0] 
Part2 = Parts[1] 
Part3 = Parts[2] 
Species_Dictionary = {'Brown Rat':'BR', 'Black Rat':'BLR', 'Dwarf Rat':'DR', 'White Mouse':'GG', 'Human':'HS', 'Brown Mouse':'VK'} 
School_List = ['UHJ', 'UMG', 'COL', 'UVT'] 
Initials_List = ['DM', 'DCM', 'YXAA', 'DJ'] 
Species_Check = 0 
School_Check = 0 
Initials_Check = 0 
# supposed to check to see if each 'part' can be found in the Species_Dictionary 
if Part1 or Part2 or Part3 in Species_Dictionary: 
    Species_Check = 1 
    print Species_Check 
else: 
    print "Cannot find a valid species" 
    return 

#check to see if any of the 'parts' can be found in the School-List 
if Part1 or Part2 or Part3 in School_List: 
    School_Check = 1 
else: 
    print "Cannot find valid school" 
    return 

#Check if any of the 'parts' are in the Initials_List 
if Part1 or Part2 or Part3 in Initials_List: 
    Initials_Check = 1 
else: 
    print "Cannot find valid initials" 
    return 

#If the previous 3 if-statements have been met, the file 'passes' and contains correct info 
if Species_Check == 1 and School_Check == 1 and Initials_Check == 1: 
    print "Your file contains correct title information" 
else: 
    print "Your file name does not contain the correct information" 
    return 
+0

對於澄清:文件名可以是任何順序。物種,姓名縮寫和學校不一定總是在第一,第二和第三位。這就是爲什麼我想通過兩個列表和字典運行不同的'部分'...因爲文件名的任何部分都可以包含種類/首字母縮寫詞/學校。沒有特定的順序。 – umgcoder

回答

1

條件if Part1 or Part2 or Part3 in Species_Dictionary:不會做你的想法。

如果文件名是DJ_BR_UVT.xls那麼partsDJBRUVT.xls。你必須刪除擴展名。

PARTS1 = ('BR','BLR','DR','GG','HS','VK') 
PARTS2 = ('UHJ', 'UMG', 'COL', 'UVT') 
PARTS3 = ('DM', 'DCM', 'YXAA', 'DJ') 
def checkFilename(filename): 
    f = filename.split('.')[0] # this removes the extension 
    parts = f.split('_') 
    nb1, nb2, nb3 = 0, 0, 0 
    for p in parts: 
    if p in PARTS1: nb1 += 1 
    if p in PARTS2: nb2 += 1 
    if p in PARTS3: nb3 += 1 
    return nb1 == 1 and nb2 == 1 and nb3 == 1 

print (checkFilename("DJ_BR_UVT.xls")) 
print (checkFilename("DJ_BR_staford.xls")) 

此打印

True 
False 
+0

很好的答案...假設這些部分真的可以是任何順序(並且文件名中沒有多個句點或文件路徑中有_個(可能或可能沒有完全指定:P),但是這應該基於提供的規範:) –