Извличане на текст — Aspose.Note FOSS за Python

Aspose.Note FOSS for Python exposes the full text content of every OneNote page through the RichText възел. Всеки RichText съдържа както обикновен текст .Text низ и .TextRuns списък от индивидуално стилизирани TextRun сегменти. Тази страница документира всеки наличен шаблон за извличане на текст.


Извличане на целия прост текст

Най‑бързият начин да получите целия текст от документ е GetChildNodes(RichText), който извършва рекурсивно обходване в дълбочина на целия DOM:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    if rt.Text:
        print(rt.Text)

Съберете в списък и ги обединете:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
all_text = "\n".join(
    rt.Text for rt in doc.GetChildNodes(RichText) if rt.Text
)

Извличане на текст по страници

Организирайте извлечения текст по заглавие на страницата:

from aspose.note import Document, Page, RichText

doc = Document("MyNotes.one")
for page in doc.GetChildNodes(Page):
    title = (
        page.Title.TitleText.Text
        if page.Title and page.Title.TitleText
        else "(untitled)"
    )
    print(f"\n=== {title} ===")
    for rt in page.GetChildNodes(RichText):
        if rt.Text:
            print(rt.Text)

Преглед на форматиращите участъци

RichText.TextRuns е списък от TextRun обекти. Всеки участък обхваща непрекъснат диапазон от знаци с еднороден TextStyle:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    for run in rt.TextRuns:
        style = run.Style
        parts = []
        if style.IsBold:          parts.append("bold")
        if style.IsItalic:        parts.append("italic")
        if style.IsUnderline:     parts.append("underline")
        if style.IsStrikethrough: parts.append("strikethrough")
        if style.IsSuperscript:   parts.append("superscript")
        if style.IsSubscript:     parts.append("subscript")
        if style.FontName:      parts.append(f"font={style.FontName!r}")
        if style.FontSize:      parts.append(f"size={style.FontSize}pt")
        label = ", ".join(parts) if parts else "plain"
        print(f"[{label}] {run.Text!r}")

Справочник за свойството TextStyle

СвойствоТипОписание
IsBoldboolУдебелен текст
IsItalicboolКурсивен текст
IsUnderlineboolПодчертан текст
IsStrikethroughboolТекст с черта през него
IsSuperscriptboolГорен индекс
IsSubscriptboolДолен индекс
FontName`strNone`
FontSize`floatNone`
FontColor`intNone`
Highlight`intNone`
Language`intNone`
IsHyperlinkboolДали този фрагмент е хипервръзка
HyperlinkAddress`strNone`

Извличане на хипервръзки

Хипервръзките се съхраняват на TextRun ниво. Проверете Style.IsHyperlink:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    for run in rt.TextRuns:
        if run.Style.IsHyperlink and run.Style.HyperlinkAddress:
            print(f"  {run.Text!r:40s} -> {run.Style.HyperlinkAddress}")

Извличане на удебелен и маркиран текст

Филтрирайте участъците по свойства на форматирането, за да изолирате конкретно съдържание:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
print("=== Bold segments ===")
for rt in doc.GetChildNodes(RichText):
    for run in rt.TextRuns:
        if run.Style.IsBold and run.Text.strip():
            print(f"  {run.Text.strip()!r}")

print("\n=== Highlighted segments ===")
for rt in doc.GetChildNodes(RichText):
    for run in rt.TextRuns:
        if run.Style.Highlight is not None and run.Text.strip():
            color = f"#{run.Style.Highlight & 0xFFFFFF:06X}"
            print(f"  [{color}] {run.Text.strip()!r}")

Извличане на текст от блокове с заглавие

Заглавията на страниците са RichText възли в Title обект. Те не се връщат от top-level GetChildNodes(RichText) на страницата, освен ако не включите the Title поддърво. Достъпете ги директно:

from aspose.note import Document, Page

doc = Document("MyNotes.one")
for page in doc.GetChildNodes(Page):
    if page.Title:
        if page.Title.TitleText:
            print("Title text:", page.Title.TitleText.Text)
        if page.Title.TitleDate:
            print("Title date:", page.Title.TitleDate.Text)
        if page.Title.TitleTime:
            print("Title time:", page.Title.TitleTime.Text)

Извличане на текст от таблици

Клетките в таблицата съдържат RichText деца. Използвайте вложени GetChildNodes извиквания:

from aspose.note import Document, Table, TableRow, TableCell, RichText

doc = Document("MyNotes.one")
for table in doc.GetChildNodes(Table):
    for row in table.GetChildNodes(TableRow):
        row_values = []
        for cell in row.GetChildNodes(TableCell):
            cell_text = " ".join(
                rt.Text for rt in cell.GetChildNodes(RichText)
            ).strip()
            row_values.append(cell_text)
        print(row_values)

Операции с текст в паметта

Замяна на текст

RichText.Replace(old_value, new_value) заменя текст в паметта през всички изпълнения:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    rt.Replace("TODO", "DONE")
##Changes are in-memory only; saving back to .one is not supported

Добавяне на текстов фрагмент

from aspose.note import Document, RichText, TextStyle

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    rt.Append(" [reviewed]")  # appends with default style
    break  # just the first node in this example

Записване на извлечения текст във файл

import sys
from aspose.note import Document, RichText

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")

doc = Document("MyNotes.one")
lines = [rt.Text for rt in doc.GetChildNodes(RichText) if rt.Text]

with open("extracted.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(lines))

print(f"Extracted {len(lines)} text blocks.")

Съвети

  • GetChildNodes(RichText) на Document търси цялото дърво, включващо всички страници, контури и елементи на контура. Извикайте го за конкретен Page за ограничаване на обхвата.
  • Винаги проверявайте rt.Text (или if rt.Text:) преди отпечатване, тъй като празни RichText възли съществуват в някои документи.
  • В Windows, пре-конфигурирайте sys.stdout на UTF-8, за да избегнете UnicodeEncodeError при печатане на знаци извън системната кодова страница.
  • TextRun има само Text и Style полета. Няма Start/End свойства за отместване; за да намерите текста на поредицата в родителя RichText.Text, търсете run.Text в rt.Text ръчно.

Вижте също

 Български