【发布时间】:2016-03-30 00:54:16
【问题描述】:
我不熟悉编码和文件检查程序的早期阶段。 我正在编写一个程序来查看文件的标题中是否包含“正确信息”。
我目前正纠结于如何检查标题的 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
【问题讨论】:
-
为了澄清:文件名可以是任何顺序。物种、缩写和学校不一定总是在第一、第二和第三位。这就是为什么我想通过两个列表和字典运行不同的“部分”......因为文件名的任何部分都可以包含 species/initials/school 。没有具体的顺序。
标签: python list python-2.7 dictionary