【问题标题】:Read custom numbering from docx using python使用 python 从 docx 读取自定义编号
【发布时间】:2021-05-06 20:41:59
【问题描述】:

我有需要从 docx 读取自定义编号的要求,我使用的是 python-docx 0.8,但它不完全支持编号。我还尝试阅读受保护的属性 para._p.pPr.numPr 但没有成功。 我试图将 docx 提取到 xml 并找到 numbering.xml 和 document.xml 之间的关系。 我在那里也没有取得任何成功,因为 numbering.xml 有公式并且它通过样式标签应用,即 ()或通过 numPr (pPr>)。我试图通过 numbering.xml 找到与 numId 的关系,但也没有运气。

word文档中的编号类似于'[0001]这个应用程序'

【问题讨论】:

  • 你能放一个你试图读取的文件的样本以及你希望输出的样子吗?
  • 示例文件:easyupload.io/x0fl10
  • 输出应该给我每个段落的编号,即 [0001]、[0002]、[0003]、[0004] 和 1.,2。等
  • 好的,我明白你要做什么了。我不认为你可以用 docx 做这个现成的。 This chain 可能有你需要的东西。
  • 我厌倦了那个链接,但它不适用于我的用例。我也没有从 python-docx 库中寻找解决方案,因为我知道它在这个用例中不起作用。

标签: python docx


【解决方案1】:

想通了!诀窍不是尝试读取 doc 一词,而是转换为 python 可以更容易处理的格式:

  1. 打开 .docx 并点击“另存为”...然后选择 .txt
  2. 这本身不起作用,我必须进一步选择 UTF-8 编码的子选项。请参见此处的图片,并注意我是在 Mac 上执行此操作的,因此您的保存屏幕可能看起来不同。

完成后,您可以像普通 txt 文件一样读取新文件,包括自定义编号,然后对其进行任何自然语言处理以隔离数字。这是我的(过于简单的)代码:

# Create array called 'doc' where each item in array is line from word doc.
with open('TEST_WORD.txt', 'r') as f:
    doc = f.readlines()

# Function to return just the first word from each line if it starts with a number or a bracket.
def return_first_number(string):
    if string[0] in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '[']:
        return string.split()[0]

# Use function to create a list just of lines that start with a number.
cleaned = [return_first_number(item) for item in doc]

# Get rid of all the "None"s. 
cleaned = [item for item in cleaned if item]

# Print final list
print(cleaned)

out: ['[0001]', '1960s', '[0002]', '1960s', '[0003]', '1960s', '[0004]', '1960s', '1.', '2.']

这绝不是您所需要的。它有一些误报(例如,以 1960 年代开头的一行表示年份),而且我只有一个单词 doc 的样本,因此也可能存在其他边缘情况。但这应该会让你走上正确的道路。

祝你好运!

【讨论】:

  • docx 文件使用 rest api 调用下载到 linux 服务器上。 python web 应用程序处理它。除非可以通过 python 本身完成,否则我无法手动打开它并保存为 .txt 或 .pdf 格式。我还尝试将 libreoffice 转换为 pdf 以处理单词 docx 的松散编号和格式。我无法使用原生 MS Word 功能转换文件格式。
  • 试试this
  • 非常感谢,但即使这个库也丢失了格式并给出 1. 而不是 [0001]
猜你喜欢
  • 2021-04-01
  • 1970-01-01
  • 2021-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多