Python 读取 RTF 文件并提取文本内容

使用 Python 的 pyth 模块可以轻松读取 RTF 文件并提取纯文本内容。以下是详细步骤:

  1. 安装 pyth 模块: 在终端中输入 pip install pyth 安装 pyth 模块。

  2. 读取 RTF 文件: 使用 pyth 模块的 pyth.parser.Parser.parse 方法读取 RTF 文件。

from pyth.plugins.rtf15.reader import Rtf15Reader

with open('example.rtf', 'r') as f:
    doc = Rtf15Reader.read(f)
  1. 提取文本内容: 使用 pyth 模块的 pyth.document.Document 类的 serialize 方法提取文本内容。
from pyth.document import Document

text = ''.join([unicode(para.serialize()) for para in Document(doc).body])
print(text)

完整代码如下:

from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.document import Document

with open('example.rtf', 'r') as f:
    doc = Rtf15Reader.read(f)

text = ''.join([unicode(para.serialize()) for para in Document(doc).body])
print(text)

注意:

  • 将 example.rtf 替换为您的 RTF 文件路径。
  • 确保已经安装了 pyth 模块。

更多信息:

Python 读取 RTF 文件并提取文本内容

原文地址: https://www.cveoy.top/t/topic/oLg3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录