所以我有了这本字典
mydict = {'name': 'Theo', 'age': '39', 'gender': 'male', 'eyecolor': 'brown'}我使用docx-mailmerge将这些数据合并到一个word文档中。
template = "myworddoc.docx"
newdoc = "mergeddoc.docx"
document = MailMerge(template)
document.merge(mydict)
document.write(newdoc)但是创建的文档是空的。我猜它只适用于kwargs??
我只能使用合并和kwargs,所以
document.merge(name='Theo', age='39', gender='male', eyecolor='brown')我真的很喜欢用字典来合并数据。
我是将字典转换为kwarg (以及如何操作),还是使用字典?
谢谢你的帮助!!
发布于 2018-11-01 05:17:55
不知道它的正式名称是什么,但我称它为“分解”运算符。
document.merge(**mydict)这会将dict解压到函数的/方法的关键字参数中。
示例:
def foo_kwargs(a=1, b=2, c=3):
print(f'a={a} b={b} c={c}')
my_dict = {'a': 100, 'b': 200, 'c': 300}
foo_kwargs(**my_dict)
# Prints a=100 b=200 c=300请注意,还有参数explode:
mylist = [1,2,3,4]
def foo_args(a, b, c, d):
print(a, b, c ,d)
foo_args(*mylist)
# Prints 1 2 3 4发布于 2020-05-14 15:34:04
在将字典传递给Mailmerge对象时使用merge_pages方法:document.merge_pages([mydict])
# keys = your mergefield names, values = what you want to insert into each mergefield
mydict = {'name': 'Theo', 'age': '39', 'gender': 'male', 'eyecolor': 'brown'}
template = "myworddoc.docx"
newdoc = "mergeddoc.docx"
document = MailMerge(template)
print([i for i in document.get_merge_fields()] # Verify your merge fields exist
document.merge_pages([mydict])
document.write(newdoc)
document.close()https://stackoverflow.com/questions/53092062
复制相似问题