Extracció de text — Aspose.Note FOSS per a Python

Aspose.Note FOSS for Python exposes the full text content of every OneNote page through the RichText node. Cada RichText conté tant un text pla .Text cadena i una .TextRuns llista d’estils individuals TextRun segments. Aquesta pàgina documenta tots els patrons d’extracció de text disponibles.


Extreu tot el text pla

La manera més ràpida d’obtenir tot el text d’un document és GetChildNodes(RichText), que realitza un recorregut recursiu en profunditat per tot el DOM:

from aspose.note import Document, RichText

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

Recull en una llista i uneix:

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
)

Extreu text per pàgina

Organitza el text extret per títol de pàgina:

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)

Inspecciona les seqüències de format

RichText.TextRuns és una llista de TextRun objectes. Cada execució cobreix un interval contigu de caràcters amb un uniform 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}")

Referència de la propietat TextStyle

PropietatTipusDescripció
IsBoldboolText en negreta
IsItalicboolText en cursiva
IsUnderlineboolText subratllat
IsStrikethroughboolText ratllat
IsSuperscriptboolSuperíndex
IsSubscriptboolSubíndex
FontName`strNone`
FontSize`floatNone`
FontColor`intNone`
Highlight`intNone`
Language`intNone`
IsHyperlinkboolSi aquest fragment és un hiperenllaç
HyperlinkAddress`strNone`

Extreu enllaços hiperenllaç

Els hiperenllaços s’emmagatzemen al TextRun nivell. Comproveu 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}")

Extreu text en negreta i ressaltat

Filtra les seqüències per propietats de format per aïllar contingut específic:

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}")

Extreu text dels blocs de títol

Els títols de pàgina són RichText nodes dins del Title objecte. No es retornen per un nivell de primer nivell GetChildNodes(RichText) a la pàgina tret que inclogui el Title subarbre. Accediu-hi directament:

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)

Extreu text de taules

Les cel·les de la taula contenen RichText fills. Utilitzeu anidats GetChildNodes crides:

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)

Operacions de text en memòria

Substituir text

RichText.Replace(old_value, new_value) substitueix text en memòria en totes les execucions:

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

Afegir un fragment de text

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

Desar el text extret a un fitxer

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.")

Consells

  • GetChildNodes(RichText) en un Document cerca el complet arbre que inclou totes les pàgines, esquemes i elements d’esquema. Crida-ho en un específic Page per limitar l’abast.
  • Comproveu sempre rt.Text (o if rt.Text:) abans d’imprimir, com a buit RichText existeixen nodes en alguns documents.
  • En Windows, reconfigura sys.stdout a UTF-8 per evitar UnicodeEncodeError en imprimir caràcters fora de la pàgina de codis del sistema.
  • TextRun té només Text i Style camps. No hi ha Start/End propietats d’offset; per localitzar el text d’un run dins del pare RichText.Text, cerca run.Text dins rt.Text manualment.

Vegeu també

 Català