【问题标题】:How to write code to MS Word using python retaining the formatting?如何使用保留格式的python将代码写入MS Word?
【发布时间】:2021-01-31 06:18:35
【问题描述】:

我想创建一个 MS Word 文档,它编译了很多我现有的代码(在 MATLAB 和 Python 中)。我是用 python-docx 写的。

如果我这样做:

file = open('task1.m', 'r')
document.add_paragraph(file)

然后代码以简单文本格式用 MS word 编写,无需格式化。

有没有什么方法可以在编写代码的同时保留编程语言格式? (保持颜色不变)

【问题讨论】:

    标签: python python-docx


    【解决方案1】:

    .m 文件不包含颜色信息。这是由您使用的任何 IDE/编辑器添加的。

    如果您知道(或可以找到)如何将 html 格式或 rtf 格式的文本插入到您的 word 文档中,请查看pygments 模块。

    我不确定如何将这种 rtf 格式的文本写入 word 文档。但是,如果您将其写入 RTF 文档,则可以通过 Word 将其打开并保存。

    假设我运行这段代码toword.py:

    from docx import Document
    
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import RtfFormatter
    
    with open("toword.py", "r") as f:
        code = f.read()
        
    ht = highlight(code, PythonLexer(), RtfFormatter())
    
    with open("rtffile.rtf", "w") as wf:
        wf.write(ht)
        
    doc = Document()
    paragraph = doc.add_paragraph(ht)
    doc.save("code.docx")
    

    还有一个pygments.lexers.matlab.MatlabLexer 格式的 Matlab 文件。或者您可以使用 pygments.lexers.get_lexer_for_filename(filename) 从文件名中获取词法分析器。

    在 Word 中打开 rtffile.rtf

    在 Word 中打开code.docx


    或者,您可以使用pandoc 模块及其backend。如果你提供一些markdown,它可以转换为docx格式,如果markdown包含代码围栏,它可以自动突出显示。

    所以用这段代码:

    # from docx import Document
    
    from pygments import highlight
    from pygments.lexers import PythonLexer
    from pygments.formatters import HtmlFormatter
    
    import pandoc
    
    with open("toword.py", "r") as f:
        code = f.read()
    
    md = f"`````python\n{code}\n`````";
    doc = pandoc.Document()
    doc.markdown = bytearray(md, encoding="utf-8")
    doc.add_argument("out=code.docx")
    doc.docx
    

    我们得到以下code.docx

    您可以使用--highlight-style=... 参数来使用突出显示样式。更多信息here

    【讨论】:

    • 这就像代码的魅力。但是我可以用它来制作一个完整的word文档吗? (添加标题、图片等)
    • 我没试过,不过看看markdown syntax。您可以包括标题和图像。大概 pandoc 应该对那些没问题。
    • 我在github上添加了一个简单的例子,以防万一。
    【解决方案2】:

    为了以一种快速而肮脏的方式来实现这一点,NotePad++ 有一个功能,您可以在其中为您的语言打开语法突出显示。然后,选择代码,右键单击并选择“插件命令 > 使用语法突出显示复制文本”。 现在,您可以将其粘贴到 Word 中,颜色仍然保留。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-08
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多