简体   繁体   English

Python 通过 python 在 MS 字中打印和(和)字符

[英]Python printing & (and) character in MS word through python

I am generating MS word files through Python using docxtpl .我正在使用docxtpl通过 Python 生成 MS word 文件。 I am trying to import the Humanities&Social Sciences text into an MS word file.我正在尝试将Humanities&Social Sciences文本导入 MS word 文件。 But, I see Humanities Sciences printed in MS word.但是,我看到Humanities Sciences是用 MS word 打印的。

I tried these combinations, but they did not work: Humanities&&Social Sciences , Humanities\&Social Sciences .我尝试了这些组合,但它们不起作用: Humanities&&Social SciencesHumanities\&Social Sciences What should I write in python so that when I import it into MS word, I see the full and complete text?我应该在 python 中写什么,这样当我将其导入 MS Word 时,我可以看到完整的文本?

How Escaping works in docxtpl is given below. Escaping 如何在docxtpl中工作如下。 Following this will solve your issue.遵循这将解决您的问题。

By default, no escaping is done.默认情况下,没有 escaping 完成。

When you use a {{ }}, under the hood, you are modifying an XML word document, this means you cannot use all chars, especially <, > and &.当您使用 {{ }} 时,实际上是在修改 XML word 文档,这意味着您不能使用所有字符,尤其是 <、> 和 &。 In order to use them, you must escape them.为了使用它们,你必须逃避它们。 There are 4 ways:有4种方式:

    context = { 'var':R('my text') } and {{r <var> }} in the template (note the r),
    context = { 'var':'my text'} and {{ <var>|e }} in your word template
    context = { 'var':escape('my text')} and {{ <var> }} in the template.
    enable autoescaping when calling render method: tpl.render(context, autoescape=True) (default is autoescape=False)

See tests/escape.py example for more informations.有关更多信息,请参阅 tests/escape.py 示例。

Another solution, if you want to include a listing into your document, that is to escape the text and manage \n, \a, and \f you can use the Listing class另一种解决方案,如果您想在文档中包含一个列表,即转义文本并管理 \n、\a 和 \f,您可以使用列表 class

in your python code:在您的 python 代码中:

context = { 'mylisting':Listing('the listing\nwith\nsome\nlines \a and some paragraph \a and special chars : <>&') }

in your docx template just use {{ mylisting }}在您的 docx 模板中只需使用{{ mylisting }}

With Listing(), you will keep the current character styling (except after a \a as you start a new paragraph).使用 Listing(),您将保持当前的字符样式(除非在您开始新段落的 \a 之后)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM