我是新來編碼和工作在文件檢查程序的早期階段。 我正在編寫一個程序,以查看文件是否在其標題中包含「正確信息」。驗證文件名的一部分存在於字典或列表中,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
對於澄清:文件名可以是任何順序。物種,姓名縮寫和學校不一定總是在第一,第二和第三位。這就是爲什麼我想通過兩個列表和字典運行不同的'部分'...因爲文件名的任何部分都可以包含種類/首字母縮寫詞/學校。沒有特定的順序。 – umgcoder