【问题标题】:Sort MS Word paragraphs alphabetically with Python使用 Python 按字母顺序对 MS Word 段落进行排序
【发布时间】:2021-11-11 13:53:24
【问题描述】:

如何使用 python-docx 按字母顺序对 MS Word 段落进行排序?

我尝试了几件事,但无法正常工作。 像下面这样的代码可以完成这项工作吗?

from docx import Document

document = Document()
document.add_paragraph('B - paragraph two' )
document.add_paragraph('A - paragraph one' )

document.paragraphs.sort(key=lambda x: x.text)

document.save('sorted_paragraphs.docx')

sorted_paragraphs.docx 中的预期结果:

A - paragraph one
B - paragraph two

ie:有没有办法像MS word GUI sort 用 python 做同样的事情?

重点是更改文档中段落的位置,以便根据段落首字母按字母顺序显示。

【问题讨论】:

  • 我假设您的代码开头缺少import ....?否则我只会得到NameError: name 'Document' is not defined
  • 确实,我编辑了我的问题。你也需要pip3 install python-docx
  • 您真的要更改文档中段落的位置吗?还是您只想按字母顺序处理段落?
  • @scanny,是的,我确实想更改文档中段落的位置,以便根据段落首字母按字母顺序显示(为了清楚起见,我编辑了我的问题,谢谢)。

标签: python-3.x sorting ms-word python-docx


【解决方案1】:

这样的事情应该可以解决问题:

# --- range of paragraphs you want to sort, by paragraph index
# --- note that the last paragraph (18) is not included, consistent
# --- with Python "slice" notation.
start, end = 8, 18

# --- create a sorted list of tuples (pairs) of paragraph-text (the
# --- basis for the sort) and the paragraph `<w:p>` element for each
# --- paragraph in range.
text_element_triples = sorted(
    (paragraph.text, i, paragraph._p)
    for i, paragraph in enumerate(document.paragraphs[start:end])
)

# --- move each paragraph element into the sorted position, starting
# --- with the first one in the list
_, _, last_p = text_element_triples[0]

for _, _, p in text_element_triples[1:]:
    last_p.addnext(p)
    last_p = p

【讨论】:

  • 这适用于大多数文件,谢谢。但是我不时收到错误'sorted((paragraph.text,paragraph._p)for paragraph in doc.paragraphs [start:end])TypeError:'CT_P'和'CT_P'的实例之间不支持'
  • 好的,我做了一个小改动,我认为可以解决这个问题。当两个段落的文本完全匹配时,就会出现问题。在这种情况下,排序算法将尝试对&lt;w:p&gt; 元素(CT_P 对象)进行排序以“打破平局”。似乎这些元素不可订购。插入段落的索引可以解决这个问题,因为它既具有可比性又始终是唯一的,因此永远不会比较 w:p 元素。
猜你喜欢
  • 1970-01-01
  • 2022-10-07
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多