使用 Python 提取 OneNote 文件中的文本

如果您需要读取 Microsoft OneNote 中的文本 .one 在 Python 脚本中读取文件,而无需安装 Microsoft Office 或运行 Windows,, Aspose.Note FOSS for Python 是解决方案。它是一个 100% 免费、开源的库,直接解析 OneNote 二进制格式并提供简洁的 Python API。.

安装

pip install aspose-note

无需 API 密钥。无需许可证文件。无需 Microsoft Office。.


最简方法:GetChildNodes(RichText)

OneNote 文本存储在 RichText 跨页面、提纲和提纲元素分布的节点中。. GetChildNodes(RichText) 对整个文档树执行递归搜索,并将每个文本节点作为扁平列表返回::

from aspose.note import Document, RichText

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

这是从 .one 文件中获取所有文本内容的最快方式。.


将文本保存到文件

from aspose.note import Document, RichText

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"Saved {len(lines)} text blocks to extracted.txt")

逐页提取文本

当您需要了解每个文本块来自哪一页时::

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)"
    )
    page_texts = [rt.Text for rt in page.GetChildNodes(RichText) if rt.Text]
    print(f"\n=== {title} ===")
    for text in page_texts:
        print(text)

提取超链接

超链接存储在单个 TextRun 对象中,位于 RichText 节点。检查 run.Style.IsHyperlink:

from aspose.note import Document, RichText

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

检测格式:粗体、斜体、下划线

每个 TextRun 通过其携带每字符的格式化。 TextStyle:

from aspose.note import Document, RichText

doc = Document("MyNotes.one")
for rt in doc.GetChildNodes(RichText):
    for run in rt.Runs:
        s = run.Style
        if any([s.Bold, s.Italic, s.Underline]):
            flags = ", ".join(f for f, v in [
                ("bold", s.Bold), ("italic", s.Italic), ("underline", s.Underline)
            ] if v)
            print(f"[{flags}] {run.Text.strip()!r}")

从流读取

支持云存储、HTTP 响应体或内存缓冲区::

import io, urllib.request
from aspose.note import Document, RichText

##Example: load from bytes already in memory
one_bytes = open("MyNotes.one", "rb").read()
doc = Document(io.BytesIO(one_bytes))
texts = [rt.Text for rt in doc.GetChildNodes(RichText) if rt.Text]
print(f"Extracted {len(texts)} text block(s)")

Windows 编码修复

在 Windows 终端上,, sys.stdout 可能使用会在 Unicode 字符上崩溃的旧编码。请在脚本开头添加以下内容::

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

库支持的内容

功能已支持
读取 .one 文件(路径或流)
提取 RichText.Text (纯文本)
检查 TextRun.Style (粗体、斜体、超链接、字体)
从表格单元格中提取文本
读取页面标题
写回到 .one
加密文档

后续步骤