在python docx模块中使用段落功能时减少垂直空间

2023-12-25

我正在添加单行文本,例如此字符串=“这只是一些文本。”对 Word 文档使用 docx.paragraph 函数。它工作得很好,除了我想减少文本之间的垂直间距。我有什么想法可以做到这一点。

谢谢。


我创建了一个测试文档,前两个段落以正常间距隔开,接下来的两个段落以更大的间距隔开:

前两段具有以下结构(document.xml,请参阅Tag Wiki https://stackoverflow.com/tags/docx/info)

<w:p w:rsidR="009565D8" w:rsidRDefault="009336B0">
<w:r>
<w:t>Test</w:t>
</w:r>
</w:p>
<w:p w:rsidR="009336B0" w:rsidRDefault="009336B0">
<w:r>
<w:t>
Test
</w:t>
</w:r>
</w:p>

带间距的段落如下所示:

<w:p w:rsidR="009336B0" w:rsidRDefault="009336B0" w:rsidP="009336B0">
<w:pPr>
<w:spacing w:line="480" w:lineRule="auto"/>
</w:pPr>
<w:r>
<w:t>Test2</w:t>
</w:r>
</w:p>
<w:p w:rsidR="009336B0" w:rsidRDefault="009336B0" w:rsidP="009336B0">
<w:pPr>
<w:spacing w:line="480" w:lineRule="auto"/>
</w:pPr>
<w:r>
<w:t>Test2</w:t>
</w:r>
<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:bookmarkEnd w:id="0"/>
</w:p>

正如你所看到的,有一个<w:pPr>包含标签属性的标签,包括间距。

您现在应该可以通过更改来更改 docx.py段落功能。

这是段落函数:

def paragraph(paratext, style='BodyText', breakbefore=False, jc='left'):
    """
    Return a new paragraph element containing *paratext*. The paragraph's
    default style is 'Body Text', but a new style may be set using the
    *style* parameter.

    @param string jc: Paragraph alignment, possible values:
                      left, center, right, both (justified), ...
                      see http://www.schemacentral.com/sc/ooxml/t-w_ST_Jc.html
                      for a full list

    If *paratext* is a list, add a run for each (text, char_format_str)
    2-tuple in the list. char_format_str is a string containing one or more
    of the characters 'b', 'i', or 'u', meaning bold, italic, and underline
    respectively. For example:

        paratext = [
            ('some bold text', 'b'),
            ('some normal text', ''),
            ('some italic underlined text', 'iu')
        ]
    """
    # Make our elements
    paragraph = makeelement('p')

    if not isinstance(paratext, list):
        paratext = [(paratext, '')]
    text_tuples = []
    for pt in paratext:
        text, char_styles_str = (pt if isinstance(pt, (list, tuple))
                                 else (pt, ''))
        text_elm = makeelement('t', tagtext=text)
        if len(text.strip()) < len(text):
            text_elm.set('{http://www.w3.org/XML/1998/namespace}space',
                         'preserve')
        text_tuples.append([text_elm, char_styles_str])
    pPr = makeelement('pPr')
    pStyle = makeelement('pStyle', attributes={'val': style})
    pJc = makeelement('jc', attributes={'val': jc})
    pPr.append(pStyle)
    pPr.append(pJc)

    ###   Added Content from edi9999:
        Here you should add a children to the pPr element
        spacing= makeelement('spacing',attributes={'line':480,'lineRule':'auto'})
        pPr.append(spacing)
    ###

    # Add the text to the run, and the run to the paragraph
    paragraph.append(pPr)
    for text_elm, char_styles_str in text_tuples:
        run = makeelement('r')
        rPr = makeelement('rPr')
        # Apply styles
        if 'b' in char_styles_str:
            b = makeelement('b')
            rPr.append(b)
        if 'i' in char_styles_str:
            i = makeelement('i')
            rPr.append(i)
        if 'u' in char_styles_str:
            u = makeelement('u', attributes={'val': 'single'})
            rPr.append(u)
        run.append(rPr)
        # Insert lastRenderedPageBreak for assistive technologies like
        # document narrators to know when a page break occurred.
        if breakbefore:
            lastRenderedPageBreak = makeelement('lastRenderedPageBreak')
            run.append(lastRenderedPageBreak)
        run.append(text_elm)
        paragraph.append(run)
    # Return the combined paragraph
    return paragraph
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在python docx模块中使用段落功能时减少垂直空间 的相关文章

  • 不能在jinja2宏中使用current_user?

    我使用 Flask Login 它提供了current user模板中的对象 我想编写一个宏来显示评论表单或登录链接 具体取决于用户是否登录 如果我直接在模板中使用此代码 它会起作用 if current user is authentic
  • Python - 定义常量列表或字典的最佳/最简洁的方法

    第一次使用堆栈溢出 我很高兴来到这里 简介 我最近开始了 Python 编程世界的神奇冒险 我喜欢它 现在 在我从 C 语言的尴尬过渡中 一切都进展顺利 但我在创建与标头文件 h 同义的内容时遇到了麻烦 问题 我有中等大小的字典和列表 大约
  • 在 MacOSX10.6 上运行 python 服务器时 MySQLdb 错误

    运行我的服务器 python manage py runserver 产生以下错误 django core exceptions ImproperlyConfigured 加载 MySQLdb 模块时出错 没有名为 MySQLdb 的模块
  • Flask/Apache 提交按钮用于文件上传

    我有一个在 apache 后面运行的 Flask 应用程序 在我的 index html 页面上有一个文件上传按钮和一个提交按钮 如下所示
  • 插入多行并返回主键时 Sqlalchemy 的奇怪行为

    插入多行并返回主键时 我注意到一些奇怪的事情 如果我在 isert 查询中添加使用参数值 我会得到预期的行为 但是当将值传递给游标时 不会返回任何内容 这可能是一个错误还是我误解了什么 我的sqlachemy版本是0 9 4 下面如何重现错
  • 使用opencv+picamera流IO用树莓派捕获视频

    我使用 Raspberry 来简单地显示一个视频 目前仅此 为此 我必须使用 opencv cv2 我尝试了很多解决方案 但现在我想使用 Picamera 库捕获视频 我将向您展示我的代码 import io import time imp
  • 在 PyCharm 中运行命令行命令

    你好 我正在使用Python 但之前从未真正使用过它 我收到一些命令 需要在终端中运行 基本上 python Test py GET feeds 我正在使用 PyCharm 我想知道是否有办法从该 IDE 中运行这些相同的命令 按 Alt
  • Pythoncom - 将相同的 COM 对象传递给多个线程

    你好 对于 COM 对象 我是一个完全的初学者 非常感谢任何帮助 我正在开发一个Python程序 该程序应该以客户端 服务器的方式读取传入的MS Word文档 即客户端发送一个请求 一个或多个MS Word文档 服务器使用pythoncom
  • Tensorflow 到 ONNX 的转换

    我目前正在尝试转换我使用本教程创建的已保存 且正在工作 的 pb 文件 https github com thtrieu darkflow https github com thtrieu darkflow 到 onnx 文件中 我目前正在
  • 如何使用lxml和python更新xml文件?

  • 使用 python 写入 aws lambda 中的 /tmp 目录

    Goal 我正在尝试将 zip 文件写入 python aws lambda 中的 tmp 文件夹 因此我可以在压缩之前提取操作 并将其放入 s3 存储桶中 Problem 操作系统 Errno30 只读文件系统 这段代码在我的计算机上进行
  • python 和 android 中通过 AES 算法加密和解密

    我有用于 AES 加密的 python 和 android 代码 当我在android中加密文本时 它在python上成功解密 但无法在android端解密 有人有想法吗 Python代码 import base64 import hash
  • 使用 Matplotlib、PyQt 和 Threading 进行实时绘图导致 python 崩溃

    我一直在努力研究我的 Python 应用程序 但找不到任何答案 我有 PyQT GUI 应用程序 它使用 Matplotlib 小部件 GUI 启动一个新线程来处理 mpl 小部件的绘图 恐怕我现在通过从另一个线程访问 matplotlib
  • pip-tools 的干净设置不会编译非常基本的 pyproject.toml

    使用全新的pip tools设置总是会导致Backend subprocess exited error pyproject toml project dependencies openpyxl gt 3 0 9 lt 4 在仅包含上述 p
  • 如何在 Python 中包含 PHP 脚本?

    我有一个 PHP 脚本 news generator php 当我包含它时 它会抓取一堆新闻项并打印它们 现在 我在我的网站 CGI 中使用 Python 当我使用 PHP 时 我在 新闻 页面上使用了这样的内容 为了简单起见 我删掉了这个
  • 找到图像特征宽度的正确方法和Python包

    输入是一个在黑色背景上带有彩色 抱歉 垂直线的光谱 给定该带的近似 x 坐标 用 X 标记 我想找到该带的宽度 我对图像处理不熟悉 请引导我前往正确的方法图像处理和Python图像处理package也能起到同样的作用 我认为 PIL Ope
  • 如何在 Flask 中获取 POSTed JSON?

    我正在尝试使用 Flask 构建一个简单的 API 现在我想在其中读取一些 POSTed JSON 我使用 Postman Chrome 扩展进行 POST 我 POST 的 JSON 很简单 text lalala 我尝试使用以下方法读取
  • 磁盘寻道时间测量方法

    我编写了一个脚本来测量 HDD 上的寻道时间 并且其完成方式的微小变化会导致显着不同的时间 第一个周期在磁盘开头的区域内进行跳转 第二个周期选择磁盘上执行查找的随机区域 相同大小 这种方法显然不同 但我不明白为什么它会改变结果 请注意 对于
  • 从 xgb.train() 获取概率

    我是 Python 和机器学习的新手 我在网上搜索了我的问题 并尝试了人们建议的解决方案 但仍然没有得到它 如果有人能帮助我 我将非常感激 我正在开发我的第一个 XGboost 模型 我已经使用 xgb XGBClassifier 调整了参
  • Pymongo 批量插入

    我正在尝试批量插入文档 但批量插入时不会插入超过 84 个文档 给我这个错误 in insert pymongo errors InvalidOperation cannot do an empty bulk insert 是否可以批量插入

随机推荐