Python 读取 RTF 文件并提取文本内容
Python 读取 RTF 文件并提取文本内容
使用 Python 的 pyth 模块可以轻松读取 RTF 文件并提取纯文本内容。以下是详细步骤:
-
安装 pyth 模块: 在终端中输入
pip install pyth安装pyth模块。 -
读取 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)
- 提取文本内容: 使用
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模块。
更多信息:
pyth模块文档: https://pypi.org/project/pyth/
原文地址: https://www.cveoy.top/t/topic/oLg3 著作权归作者所有。请勿转载和采集!