【问题标题】:Count the total number of bullets used in a word document计算word文档中使用的项目符号总数
【发布时间】:2018-03-12 18:10:46
【问题描述】:

我有一个文档,其中有项目符号和数字中的文本。我想查找 word 文档的项目符号总数和编号。

这是我尝试过的示例文本:

这是对word文档的子弹测试

• 让我们为此努力以玩成名游戏
• 在蜡烛变暗之前点亮灯泡
• 像没有明天一样奔跑

我也输入数字,因为我想计算子弹和数字

  1. 这是一个数字
  2. 这是另一个号码
  3. 数字太多了

我已经尝试了以下代码:

my_file = "Bullet_test.docx"
    from docx import Document
    document = Document(my_file)
    styles = document.styles

阅读子弹

from docx.enum.style import WD_STYLE_TYPE
   paragraph_styles = [
        s for s in styles if s.type == WD_STYLE_TYPE.PARAGRAPH
        ]
   paragraph_styles

我得到以下输出:

[_ParagraphStyle('Normal') id: 106125072,
    _ParagraphStyle('List Paragraph') id: 106126528]

我想找到项目符号和编号的总数,对于示例 word 文档,我总共应该有 6 个。请让我知道我做错了什么。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您做错的事情是试图通过遍历styles 来查找项目符号,即使在您的文档中,您没有名为Bulletstyle 或类似的东西。

    如果您想使用style 来查找项目符号,您必须将它们定义为一种样式(通过添加一个名为“Bullet”的样式)。

    这是我在我的机器上所做的:

    之后我运行了这个:

    >>> d = Document(my_file)
    >>> d.styles
    <docx.styles.styles.Styles object at 0x026B4830>
    >>> d.styles['Bullet'] # to check that indeed the style 'Bullet' exists
    _ParagraphStyle('Bullet') id: 40587152
    >>> for p in d.paragraphs:
    ...     if p.style.name == 'Bullet':
    ...             print '~'
    ...
    

    瞧,发现了 4 颗子弹!

    ~
    ~
    ~
    ~
    

    可以直接使用 Python 添加样式,方法是(取自here):

    >>> from docx.enum.style import WD_STYLE_TYPE
    >>> styles = document.styles
    >>> style = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)
    >>> style.name
    'Citation'
    >>> style.type
    PARAGRAPH (1)
    

    然后通过以下方式应用它:

    >>> document = Document()
    >>> paragraph = document.add_paragraph()
    >>> paragraph.style
    <docx.styles.style._ParagraphStyle object at <0x11a7c4c50>
    >>> paragraph.style.name
    'Normal'
    >>> paragraph.style = document.styles['Heading 1']
    >>> paragraph.style.name
    'Heading 1'
    

    【讨论】:

    • 感谢@CIsForCookies 的回答。对于我正在做的项目,我会从各种来源获得大量 word 文档,因此可能无法为文档添加样式。有没有其他方法可以找到 word 文档中的项目符号总数?谢谢!
    • 不确定...从我在这里看到的http://python-docx.readthedocs.io/en/latest/user/styles-understanding.htmlList Bullet 是默认样式,因此您可以在不创建和应用样式的情况下使用它,但出于某种原因,我保证它不存在
    • 我曾尝试为你点赞,但它说它不会显示为点赞,但点赞已被注册。
    猜你喜欢
    • 2013-06-23
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2011-01-19
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多