在python中怎么读取rtf文件并输出text文本
可以使用pyth翻译文本模块pyth来读取rtf文件并输出text文本,具体步骤如下:
-
安装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)
- 提取text文本:使用pyth模块的
pyth.document.Document类的serialize方法提取text文本。
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)
``
原文地址: https://www.cveoy.top/t/topic/hirR 著作权归作者所有。请勿转载和采集!