小编drj*_*ild的帖子

Python - 从docx文件中删除页眉和页脚

我需要在许多docx文件中删除页眉和页脚.我当前正在尝试使用python-docx库,但此时它不支持docx文档中的页眉和页脚(正在进行中).

有没有办法在Python中实现这一点?

据我所知,docx是一种基于xml的格式,但我不知道如何使用它.

PSI有一个想法,使用lxml或BeautifulSoup来解析xml并替换一些部分,但它看起来很脏

UPD.感谢Shawn,这是一个很好的起点.我对脚本做了一些修改.这是我的最终版本(它对我有用,因为我需要编辑许多.docx文件.我使用的是BeautifulSoup,因为标准的xml解析器无法获得有效的xml-tree.而且,我的docx文档没有它们只是将页眉和页脚的图像放在页面的顶部.另外,为了提高速度,你可以使用lxml而不是Soup.

import zipfile
import shutil as su
import os
import tempfile
from bs4 import BeautifulSoup


def get_xml_from_docx(docx_filename):
    """
        Return content of document.xml file inside docx document
    """
    with zipfile.ZipFile(docx_filename) as zf:
        xml_info = zf.read('word/document.xml')
    return xml_info


def write_and_close_docx(self, edited_xml, output_filename):
    """ Create a temp directory, expand the original docx zip.
        Write the modified xml to word/document.xml
        Zip it up as the new docx
    """
    tmp_dir = tempfile.mkdtemp()

    with zipfile.ZipFile(self) as zf:
        zf.extractall(tmp_dir)

    with open(os.path.join(tmp_dir, 'word/document.xml'), 'w') …
Run Code Online (Sandbox Code Playgroud)

python docx python-docx

6
推荐指数
1
解决办法
2285
查看次数

Python。为从单独模块导入的类实例启用日志记录

再会。我正在尝试解决Python 中的登录问题。我正在使用Python 3.5.1。我有一个应用程序,它使用从其他模块导入的类。我无法为其启用日志记录。这是一个简单的表示:

# test.py
import logging

from test_class import TestClass


logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler('test_log.log', mode='w'))


if __name__ == '__main__':
    logger.info('Importing class')
    t = TestClass()
    t.make_call()
    t.make_another_call()
    logger.info('End')

# test_class.py
import logging


class TestClass(object):

    def __init__(self):
        self.logger = logging.getLogger('test_class.TestClass')

    def make_call(self):
        self.logger.info('Make a call')

    def make_another_call(self):
        self.logger.info('Make another call')
Run Code Online (Sandbox Code Playgroud)

如您所见,记录器必须写入文件行(两行来自主模块,两行来自类。但是当我打开日志文件时,我看到:

# test_log.log
Importing class
End
Run Code Online (Sandbox Code Playgroud)

因此,来自类的两个记录器调用没有效果。知道吗,为什么它不起作用?先感谢您。

python logging python-3.x python-3.5

3
推荐指数
1
解决办法
8699
查看次数

标签 统计

python ×2

docx ×1

logging ×1

python-3.5 ×1

python-3.x ×1

python-docx ×1