gpt4 book ai didi

c# - 如何使用 Word.Interop 获取每个标题下的段落

转载 作者:行者123 更新时间:2023-12-02 16:11:01 29 4
gpt4 key购买 nike

我有一些这样的示例文本:

1 Header
bla bla bla...
bla bla bla...
1.1 SubHeader
bla bla bla...
bla bla bla...

我阅读了 .docx 的每一页文件,我想将标题下的段落和标题存储为字典:

{"1 Header", "bla bla bla"...},
{"1.1 Subheader", "bla bla bla"...},

其中键是 string ( header 名称),值为 ParagraphsList<Paragraph>

我知道这可以用 Selection() 来完成,但我不知道如何使用它。

for (int i = 1; i<=paragraphCollection.Count;i++)
{
if (isHeader(paragraphCollection[i].Range.Text) || isSubHeader(paragraphCollection[i].Range.Text))
{
//collect paragraphs until we find another header or subheader
}
}

最佳答案

我通常使用 VBA 尝试算法并将其转换为 C#..

C# 很强大,但是当涉及到 MS Word 的对象引用时,VBA 更好。

阅读我的代码并将其翻译成您的 C# 代码。我认为遍历所有段落并不可取。

(已更新)此算法适用于二维结构的字典。

如果你想要像JSON这样的结构,你需要解析文档。在那种情况下,我认为解析 .docx xml 结构比使用 MS word 对象和方法更好。

另外,我没有考虑文档的第一段不是标题的地方。

Sub IteratingHeadingsForDoSomething()

listHeadingsString = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading) ' Collection of heading strings, No location info
headingsCount = UBound(listHeadingsString)

Selection.GoTo What:=wdGoToHeading, Which:=wdGoToFirst 'goto first heading
For i = 1 To headingsCount Step 1

Debug.Print listHeadingsString(i) ' put this to the list
Debug.Print Selection.Range.Paragraphs.OutlineLevel ' use outline level

SelectNextParagraph
If IsOutlineLevel(Selection) = True Then
' para under the heading is also a heading
Debug.Print "This is a heading too" ' >>> Skip storing??
GotoPreviousHeading ' go back to previous heading
Else
Do Until IsOutlineLevel(Selection) = True
Debug.Print Selection.Range.Text '>>> Store paragraph separately or concatenatively
SelectNextParagraph
Loop
GotoPreviousHeading
End If


GoToNextHeading
Next i

End Sub
'//////////////////////////////////////////
Sub GoToNextHeading()

Selection.GoTo What:=wdGoToHeading, Which:=wdGoToNext

End Sub
'//////////////////////////////////////////
Sub GotoPreviousHeading()

Selection.GoTo What:=wdGoToHeading, Which:=wdGoToPrevious

End Sub
'//////////////////////////////////////////
Sub SelectNextParagraph()

Selection.Next(Unit:=wdParagraph, Count:=1).Select

End Sub
'//////////////////////////////////////////
Function IsOutlineLevel(mySelection As Selection) As Boolean

If mySelection.Range.Paragraphs.OutlineLevel = wdOutlineLevelBodyText Then
IsOutlineLevel = False
Else
IsOutlineLevel = True
End If

End Function

关于c# - 如何使用 Word.Interop 获取每个标题下的段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68008541/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com