Como inspecionar tags do OneNote em Python

Como inspecionar tags do OneNote em Python

O OneNote permite que os usuários anotem conteúdo com etiquetas coloridas: estrelas, caixas de seleção, sinalizadores importantes e rótulos personalizados. O Aspose.Note FOSS para Python expõe essas anotações como objetos NoteTag em nós RichText, Image, AttachedFile e Table por meio da propriedade .Tags. Este guia mostra como lê‑las.


Guia passo a passo

Etapa 1: Instale o Aspose.Note FOSS para Python

pip install aspose-note

Etapa 2: Carregar o arquivo .one

from aspose.note import Document

doc = Document("TaggedNotes.one")
print(f"Pages: {len(list(doc))}")

Etapa 3: Encontrar Tags em Nós RichText

A maioria das tags está anexada a blocos de texto:

from aspose.note import Document, RichText

doc = Document("TaggedNotes.one")
for rt in doc.GetChildNodes(RichText):
    for tag in rt.Tags:
        print(f"[RichText] Label={tag.Label!r}  Icon={tag.Icon}  text={rt.Text.strip()!r}")

Etapa 4: Encontrar Tags em Imagens

from aspose.note import Document, Image

doc = Document("TaggedNotes.one")
for img in doc.GetChildNodes(Image):
    for tag in img.Tags:
        print(f"[Image] Label={tag.Label!r}  filename={img.FileName!r}")

Etapa 5: Encontrar tags nas tabelas

from aspose.note import Document, Table

doc = Document("TaggedNotes.one")
for table in doc.GetChildNodes(Table):
    for tag in table.Tags:
        print(f"[Table] Label={tag.Label!r}  widths={[col.Width for col in table.Columns]}")

Etapa 6: Coletar Todas as Tags no Documento

from aspose.note import Document, RichText, Image, Table

doc = Document("TaggedNotes.one")
all_tags = []

for rt in doc.GetChildNodes(RichText):
    for tag in rt.Tags:
        all_tags.append({"type": "RichText", "Label": tag.Label,
                         "CompletedTime": tag.CompletedTime, "text": rt.Text.strip()})
for img in doc.GetChildNodes(Image):
    for tag in img.Tags:
        all_tags.append({"type": "Image", "Label": tag.Label,
                         "CompletedTime": tag.CompletedTime, "file": img.FileName})
for table in doc.GetChildNodes(Table):
    for tag in table.Tags:
        all_tags.append({"type": "Table", "Label": tag.Label,
                         "CompletedTime": tag.CompletedTime})

print(f"Total tagged items: {len(all_tags)}")
for item in all_tags:
    print(item)

Referência da Propriedade NoteTag

PropriedadeTipoDescrição
Iconint | NoneIdentificador numérico da forma da etiqueta (estrela, caixa de seleção, seta, etc.)
Labelstr | NoneString de rótulo legível por humanos (por exemplo, "Important", "To Do")
FontColorint | NoneCor do texto como inteiro ARGB
Highlightint | NoneCor de realce como inteiro ARGB
CreationTimedatetime | NoneQuando a etiqueta foi criada
CompletedTimedatetime | NoneQuando a etiqueta foi concluída (None se não concluída)
StatusTagStatusTagStatus.Completed se concluída, caso contrário TagStatus.Open

Filtrar Tags Concluídas vs Pendentes

Tags que foram marcadas (como caixas de seleção “To Do”) têm um campo não-None CompletedTime:

from aspose.note import Document, RichText

doc = Document("TaggedNotes.one")
pending, done = [], []

for rt in doc.GetChildNodes(RichText):
    for tag in rt.Tags:
        item = {"Label": tag.Label, "text": rt.Text.strip()}
        if tag.CompletedTime is None:
            pending.append(item)
        else:
            done.append(item)

print(f"Pending: {len(pending)}  Done: {len(done)}")
for p in pending:
    print(f"  [ ] {p['Label']}: {p['text']!r}")
for d in done:
    print(f"  [x] {d['Label']}: {d['text']!r}")

Criar um NoteTag (Em memória)

O método de fábrica NoteTag.CreateYellowStar() cria um nó de tag que você pode anexar ao novo conteúdo na memória:

from aspose.note import NoteTag

tag = NoteTag.CreateYellowStar()
print(f"Created tag: Icon={tag.Icon}  Label={tag.Label!r}")

A criação em memória é útil para compatibilidade de API. Como a gravação de volta para .one não é suportada, as tags criadas não podem ser persistidas no arquivo.


Problemas Comuns

Nenhuma tag encontrada (documento retorna listas de tags vazias): Nem todos os arquivos .one contêm tags. Verifique se o documento de origem tem tags visíveis no Microsoft OneNote antes de solucionar o problema no código.

tag.Label é uma string vazia: Algumas formas de tag não têm um rótulo de texto nos metadados do arquivo. Use tag.Icon para identificar o tipo de tag programaticamente.


Recursos Relacionados:

 Português