python - 计算 Microsoft Word 文件中的行数,而不考虑自动换行

标签 python ms-word text-processing data-science python-docx

我有一个 .docx Microsoft Word 文件,格式大致如下:

TAG    Lorem ipsum dolor sit amet, consectetur adipiscing 
       elit, sed do eiusmod tempor
TAG_2  Lorem ipsum dolor sit amet, consectetur adipiscing 
       elit, sed do eiusmod tempor incididunt ut labore 
       et dolore magna aliqua. Ut enim ad minim veniam, 
       quis nostrud exercitation ullamco laboris nisi 
TAG    Text text text text text text text text text text

通过自动换行实现缩进(如果在简单的 txt 编辑器中复制粘贴,上述文本将导致 3 行而不是 7 行)。

我的任务是自动计算分配给标签 s.t. 的行数。上面的文件会产生类似这样的结果:

TAG    2
TAG_2  4
TAG    1

现在我通过指定字体文件、字体大小和平均线长,然后划分线的长度(用 PIL.ImageFont.getsize() 测量)手动完成,但是这种方法确实很容易出错,并且没有涵盖所有可能的情况(例如字体在文件中更改)。
不幸的是我无法控制该文件,因此我无法在计算行数之前正确格式化它(因为原因会要求)。

有没有办法在 Python 中做到这一点?我找到了 python-docx package但它的功能似乎有点有限。

另请注意,.docx 格式不是强制性的,如果需要,我也可以将文件转换为 .odt。

附上我的设置(在 LibreOffice 中)的屏幕截图以使其更加清晰。

enter image description here

最佳答案

用VBA计算文档中所有段落的行数和字数:

Sub ParaStatsCount()
Dim Para As Paragraph
For Each Para In ActiveDocument.Paragraphs
  With Para.Range
    MsgBox .Text & vbCr & "Line Count = " & .ComputeStatistics(wdStatisticLines) & vbCr _
      & "Word Count = " & .ComputeStatistics(wdStatisticWords)
  End With
Next
End Sub

如果您可以使用 Python 自动化 Word,那么应该可以使用相同(和其他)方法。

关于python - 计算 Microsoft Word 文件中的行数,而不考虑自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48626396/

相关文章:

python - 无法在 uwsgi + nginx 部署下使用 tensorflow 模型

VBA Microsoft Word - 顺序数字

python - Matplotlib/Seaborn : how to plot a rugplot on the top edge of x-axis?

excel - 选择 Word 文档的内容并使用 VBA 将其粘贴到 Outlook 的正文中

java - 如何在 Java 中更改 Apache POI 中的 XWPFTableCell 边距?

awk - 用逗号替换行尾并在 sed/awk 中放入括号

Linux:用其他文件中的值替换文本字段

python - 从文件中删除行

python - 带有 python 脚本的游戏引擎?

python - 与 einsums 的交叉产品