因为业务需求,需要做一个可以自定义模板的导出功能,所以我使用的是关键词替换,所以就用到了 python-docx这个模块,但是在段落切分成runs匹配关键词的时候出现了把我设定好的关键词给切分成多个的情况出现,下边是我的解决办法.
def _export_day_report_word(self):
_doc = Document('../static/report-template/word/日报.docx')
_map_dict = self.__map_dict_report(0)
for _p in _doc.paragraphs:
runs = _p.runs
# 定义一个空的匹配词
_temp = ''
for run in runs:
# 若替换词的开头在 run.text 中,结尾不在,且匹配词为空,则取出替换词的开头放入匹配词
if '{' in run.text and '}' not in run.text and _temp == '':
_ext = '{' + run.text.split('{')[1]
_temp += _ext
run.text = run.text.replace(_ext, '')
continue
if _temp:
# 如果匹配词不为空 且 替换词的结尾在 run.text 中,则取出替换词的结尾放入匹配词
if '}' in run.text:
_ext = run.text.split('}')[0] + '}'
_temp += _ext
# 说明已经将替换词完整取出,根据词映射关系进行替换
run.text = run.text.replace(_ext, str(_map_dict[_temp]))
_temp = ''
else:
# 否则 将 run.text 追加放入匹配词
_temp += run.text
run.text = ''
continue
for _key, _val in _map_dict.items():
if _key in run.text:
run.text = run.text.replace(_key, str(_val))
其实很简单。在对逐个run进行匹配时进行一个验证,看你所设定的替换词开头符号包含在run中且结尾不包含在其中,则匹配下一个run,直到匹配到替换词的结尾符号终止,之后进行替换就ok了。