我制作了一个脚本,它在Excel表中循环,如下所示:
项目 |
| 国家代码 | [/tr>||
---|---|---|---|---|
sample.jpg | 苹果 | 142 | 美国 | 1564 |
sample2.jpg | 橙色 | 142 | 美国1562 |
任何时候,只要有一系列重复的变量声明,如下所示:
txt1= "name..."
W1 = 1200
H1 = 200
fontSize1 = 142
txt2= "country..."
W2 = 1200
H2 = 400
fontSize2 = 132
txt3= "code..."
W3 = 1200
H3 = 600
fontSize3 = 124
这是一个很好的线索,你最好有一个列表:
text_props = [
("name...", 1200, 200, 142),
("country...", 1200, 400, 132),
("code...", 1200, 600, 124),
]
现在你可以在一个循环中设置这些属性,这样:
setText(imageName,imgfile,txt1,fontSize1,W1,H1)
setText(imageName,imgfile,txt2,fontSize2,W2,H2)
setText(imageName,imgfile,txt3,fontSize3,W3,H3)
变为:
for txt, w, h, font in text_props:
setText(imageName, imgfile, txt, font, w, h)
在我自己的代码中,我可能会使用NamedTuple
而不是普通的tuple
,但这是另一个主题。:(
(编辑(如果你想把CSV数据换成txt
值,我认为你想做的是把密钥名称粘在那里(没有点(,比如这样:
text_props = [
("name", 1200, 200, 142),
("country", 1200, 400, 132),
("code", 1200, 600, 124),
]
然后只在iterrows
循环中执行此操作(其中您已经拥有所有数据(,而不是构建items
列表:
for _, row in df.iterrows():
item = row["item"]
if item not in files:
continue
imgfile = Image.open(f"./{item}")
for key, w, h, default_font_size in text_props:
# key is one of 'name', 'country', or 'code'.
# Not all keys have a font size, so check for one but
# use default_font_size if none is in the table.
font_size = row.get(key+'fontsize', default_font_size)
setText(
item, # name (the image filename)
imgfile, # file (from Image.open())
row[key], # txt (from the table, e.g. row['name'])
font_size, # fontSize (see above where this is determined)
w, # w (width)
h # h (height)
)