我正在尝试制作一个可以识别文件夹名称是否为项目的脚本。为此,我想使用多个if条件。但是,我很难处理例如检查文件夹名称的首字母和是否为数字所导致的ValueError。如果它是字符串,我想跳过该文件夹并检查下一个文件夹。预先感谢大家的帮助。
干杯,本恩
我尝试了While和ValueError除外:但是还没有成功。
#将项目的正确名称命名为“ YYMM_ProjectName” =“ 1908_Sample_Project”
projectnames = ['190511_Waldfee', 'Mountain_Shooting_Test', '1806_Coffe_Prime_Now', '180410_Fotos', '191110', '1901_Rollercoaster_Vision_Ride', 'Musicvideo_LA', '1_Project_Win', '19_Wrong_Project', '1903_di_2', '1907_DL_2', '3401_CAR_Wagon']
#检查条件
for projectname in projectnames:
if int(str(projectname[0])) < 3 and int(projectname[1]) > 5 and ((int(projectname[2]) * 10) + int(projectname[3])) <= 12 and str(projectname[4]) == "_" and projectname[5].isupper():
print('Real Project')
print('%s is a real Project' % projectname)
# print("Skipped Folders")
ValueError:int()以10为底的无效文字:“ E”
最佳答案
根据我对所有if的了解,...实际上使用regex匹配可能会更好。您正在解析每个字符,并期望每个单独的字符都在非常有限的字符范围内。
我尚未测试此模式字符串,因此它可能不正确或需要根据您的需要进行调整。
import re
projectnames = ['1911_Waldfee', "1908_Project_Test", "1912_WinterProject", "1702_Stockfootage", "1805_Branded_Content"]
p = ''.join(["^", # Start of string being matched
"[0-2]", # First character a number 0 through 2 (less than 3)
"[6-9]", # Second character a number 6 through 9 (single digit greater than 5)
"(0(?=[0-9])|1(?=[0-2]))", # (lookahead) A 0 followed only by any number 0 through 9 **OR** A 1 followed only by any number 0 through 2
"((?<=0)[1-9]|(?<=1)[0-2])", # (lookbehind) Match 1-9 if the preceding character was a 0, match 0-2 if the preceding was a 1
"_", # Next char is a "_"
"[A-Z]", #Next char (only) is an upper A through Z
".*$" # Match anything until end of string
])
for projectname in projectnames:
if re.match(p, projectname):
#print('Real Project')
print('%s is a real Project' % projectname)
# print("Skipped Folders")
编辑:=======================
您可以使用以下步骤逐步测试模式...
projectname = "2612_UPPER"
p = "^[0-2].*$" # The first character is between 0 through 2, and anything else afterwards
if re.match(p, projectname): print(projectname)
# If you get a print, the first character match is right.
# Now do the next
p = "^[0-2][6-9].*$" # The first character is between 0 through 2, the second between 6 and 9, and anything else afterwards
if re.match(p, projectname): print(projectname)
# If you get a print, the first and second character match is right.
# continue with the third, fourth, etc.
关于python - 使用多个if条件时如何克服ValueError?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58382568/