今天刚开始使用Python,所以如果我在这里做了一些疯狂的事情,请告诉我。我一直在努力简化代码块,以便更容易地重用它。我的目标是在每次重用期间只更新一组变量。我的最后一个工作代码是:
class_a='amstaff'
class_b='beagle'
class_c='doberman'
class_d='germanshepherd'
class_e='rottweiler'
with open(file_path +class_a+'.zip', 'rb') as class_a, open(file_path +class_b+'.zip', 'rb') as class_b, open(file_path +class_c+'.zip', 'rb') as class_c, open(file_path +class_d+'.zip', 'rb') as class_d, open(file_path +class_e+'.zip', 'rb') as class_e:
model = visual_recognition.create_classifier(
classifier_name,
amstaff_positive_examples=class_a,
beagle_positive_examples=class_b,
doberman_positive_examples=class_c,
germanshepherd_positive_examples=class_d,
rottweiler_positive_examples=class_e)
print(json.dumps(model, indent=2))
这为我节省了大量的时间从我的原始代码,但仍然需要一个公平的编辑位。所以我想我也许可以使用for循环,但我被卡在了中间。这是我到目前为止的情况,但我很难从这里着手。你知道吗
classes=["amstaff", "beagle", "doberman", "germanshepherd", "rottweiler"]
for x in classes:
with open(file_path +x+'.zip', 'rb') as x:
model = visual_recognition.create_classifier(
classifier_name,
amstaff_positive_examples=class_a,
beagle_positive_examples=class_b,
doberman_positive_examples=class_c,
germanshepherd_positive_examples=class_d,
rottweiler_positive_examples=class_e)
print(json.dumps(model, indent=2))
如果您使用的是
python 3.3
+,那么ExitStack可以用来管理所有上下文管理器。所有打开的文件将在with语句结束时自动关闭。你知道吗而且
files
将拥有打开文件的所有句柄,您可以使用这些句柄创建模型。你知道吗相关问题 更多 >
编程相关推荐