Python rtf to text

rtfparse

RTF Parser. So far it can only de-encapsulate HTML content from an RTF, but it properly parses the RTF structure and allows you to write your own custom RTF renderers. The HTML de-encapsulator provided with rtfparse is just one such custom renderer which liberates the HTML content from its RTF encapsulation and saves it in a given html file.

rtfparse can also decompressed RTF from MS Outlook .msg files and parse that.

Installation

Install rtfparse from your local repository with pip:

Installation creates an executable file rtfparse in your python scripts folder which should be in your $PATH .

Читайте также:  Html characters and symbols codes

Usage From Command Line

Use the rtfparse executable from the command line. Read rtfparse —help .

rtfparse writes logs into ~/rtfparse/ into these files:

rtfparse.debug.log rtfparse.info.log rtfparse.errors.log 

Example: De-encapsulate HTML from an uncompressed RTF file

rtfparse --rtf-file "path/to/rtf_file.rtf" --de-encapsulate-html --output-file "path/to/extracted.html" 

Example: De-encapsulate HTML from MS Outlook email file

Thanks to extract_msg and compressed_rtf, rtfparse internally uses them:

rtfparse --msg-file "path/to/email.msg" --de-encapsulate-html --output-file "path/to/extracted.html" 

Example: Only decompress the RTF from MS Outlook email file

rtfparse --msg-file "path/to/email.msg" --output-file "path/to/extracted.rtf" 

Example: De-encapsulate HTML from MS Outlook email file and save (and later embed) the attachments

When extracting the RTF from the .msg file, you can save the attachments (which includes images embedded in the email text) in a directory:

rtfparse --msg-file "path/to/email.msg" --output-file "path/to/extracted.rtf" --attachments-dir "path/to/dir" 

In rtfparse version 1.x you will be able to embed these images in the de-encapsulated HTML. This functionality will be provided by the package embedimg.

rtfparse --msg-file "path/to/email.msg" --output-file "path/to/extracted.rtf" --attachments-dir "path/to/dir" --embed-img 

In the current version the option —embed-img does nothing.

Programatic usage in python module

from pathlib import Path from rtfparse.parser import Rtf_Parser from rtfparse.renderers.de_encapsulate_html import De_encapsulate_HTML source_path = Path(r"path/to/your/rtf/document.rtf") target_path = Path(r"path/to/your/html/de_encapsulated.html") parser = Rtf_Parser(rtf_path=source_path) parsed = parser.parse_file() renderer = De_encapsulate_HTML() with open(target_path, mode="w", encoding="utf-8") as html_file: renderer.render(parsed, html_file) 

If you find a working official Microsoft link to the RTF specification and add it here, you’ll be remembered fondly.

Источник

Преобразование офисных файлов в текст

Представление документа в виде простого текста понадобится для анализа его содержимого: индексирования и поиска, классификации, предварительной проверки.

В нашем случае, стояла задача предварительного анализа (скоринга) документов по их содержимому. Верхнеуровневый процесс обработки документов построен с использованием MS Power Automate, поэтому конвертор нужно было реализовать в виде некоего облачного сервиса, доступного через HTTP.

В результате получился очень компактный сервис экстракции текста из офисных файлов, который успешно работает у нас уже несколько месяцев. Под катом — краткое описание сервиса, ссылка на репозиторий и другие полезные статьи по теме.

Преобразование файлов

Выделение текстового содержимого из разнообразных офисных файлов разного формата — задача не новая. На Хабре уже опубликовано несколько хороших статей по теме конверсии PDF, RTF, например:

  • «Cага о пакетном конвертировании pdf в text» — тут хороша и статья, и обсуждения. Это была начальная точка входа в проблему конвертации файлов.
  • Серия статей «Текст любой ценой» (PDF, RTF) — это про то, как сделать вообще все своими руками. Статья сильно утвердила в понимании, что надо пользоваться готовыми библиотеками.

После некоторого исследования и тестов различных пакетов (PyPdf2, striprtf, doc2text), я остановился на textract. Пакет хорошо документирован в части использования и инсталляции необходимый базовых компонент.

Textract очень прост и компактен в использовании. И самое главное — он позволяет вытаскивать текст из различных форматов стандартных офисных файлов: .doc , .docx , .rtf , .pdf , .xlsx , .ppt

import textract file_name encoding = "utf-8" text = textract.process(file_name).decode(encoding)

В процессе эксплуатации встречались случаи, когда файл с расширением .doc на самом деле содержал rtf . В этом случае конвертор antiword выдавал соответствующую ошибку и все, что нужно было сделать — переименовать файл и подать его на обработку снова.

Сервис конвертации

Сервис конвертирования файлов реализован на базе FastAPI. Он упаковывается и запускается в Docker контейнере.

Сервис принимает исходный файл в виде multipart/form-data и возвращает ответ в JSON формате, содержащем текст, статус конвертации и информацию об ошибках.

class ConvertResult(BaseModel): result: str text: str text_length: int file_name: str messages: str . @app.post('/convert', response_model=ConvertResult) async def convert_file(file: UploadFile = File("file_to_convert"), encoding: str = "utf-8", user_name: str = Depends(get_current_username)): . 

Авторизация

Компонент HTTP MS Power Automate, который мы использовали для вызова сервиса, умеет авторизоваться с использованием многих схем: Basic Authenticate, Client Certificate, OAuth, Raw.

Поскольку сервис ничего не хранит на своей стороне и реализует не критичный сервис, авторизация запросов была реализована на базовом уровне с использованием Basic Authentication. Совместно с протоколом https такой подход видится достаточным. А на стороне MS Power Automate прамеры аутентификации можно сохранить в raw виде.

При развертывании контейнера компоненты авторизации (логин / пароль) можно установить через параметры окружения контейнера.

Установка зависимостей textract

При сборке контейнера, как описано в документации по textract, нужно поставить утилиты, на которые пакет рассчитывает при работе. Чтобы не раздувать образ ставить можно только то, что реально планируется использовать.

Поскольку в нашем случае необходима была только конвертация из документов, из инсталляции удалены компоненты отвечающие за OCR и преобразование звуковых файлов.

Фрагмент Dockerfile выглядит так:

. RUN apt-get update && \ apt-get install -y antiword unrtf poppler-utils && \ rm -rf /var/lib/apt/lists/* && \ apt clean . 

Использование временных файлов

Определенной спецификой пакета textract является то, что на вход он принимает только файл, а не байтовый поток. Это из-за того, что по расширению файла определяется необходимый конвертер. А конверторы, зачастую — внешние CLI утилиты.

Соответственно, сервис, после получения файла на конвертацию через вызов, обязан сохранить его локально во временный файл, с учетом исходного расширения файла. Далее временный файл отправляется в textract на преобразование и после преобразования — удаляется.

Вопрос производительности в данном сервисе не является очень критичным, однако несколько улучшить ситуацию можно размещая область временных файлов в памяти, используя tmpfs . Как это сделать для Docker описано в документации.

Использование сервиса

Вызов сервиса из MS Power Automate

Основное назначение сервиса — выделять текст из документа в рамках одного из шагов процесса. В этом случае сервис вызывается через компонент «HTTP».

Поскольку сервис принимает на вход файл в составе multipart\form-data , отправка запроса должна быть описана в определенном формате в разделе Body как показано на картинке.

Вызов сервиса из MS Power Automate

При завершении вызова текст можно получить из поля ответа:

API сервиса

Для того, чтобы использовать сервис из различных приложений, вместе с сервисом разработан API пакет.

Пакет предоставляет классы синхронного и асинхронного клиентов для сервиса. Использование сервиса в этом случае выглядит примерно так:

from file_to_text import ConverterClient client = ConverterClient('', '', '') text = client.convert(filepath='')

Репозиторий

Готовая к использованию реализация сервиса и API доступны в репозитории на GitHub.

Буду рад комментариям и улучшениям.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Stripping rtf to plain old text

License

joshy/striprtf

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This is a simple library to convert rtf files to python strings. A lot of medical documents are written in rtf format which is not ideal for parsing and further processing. This library converts it to plain old text.

from striprtf.striprtf import rtf_to_text rtf = "some rtf encoded string" text = rtf_to_text(rtf) print(text)

If you want to use a different encoding than cp1252 you can pass it via the parameter encoding . This is only taken into account if no explicit codepage has been set.

from striprtf.striprtf import rtf_to_text rtf = "some rtf encoded string in latin1" text = rtf_to_text(rtf, encoding="latin-1") print(text)

Sometimes UnicodeDecodingErrors can happen because of various reasons. In this case you can try to relax the encoding process like this:

from striprtf.striprtf import rtf_to_text rtf = "some rtf encoded string" text = rtf_to_text(rtf, errors="ignore") print(text)

If you don’t want to install, there is also an online version available at https://striprtf.dev which can be used for free.

Pyth was not working for the rtf files I had. The next best thing was this gist: https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676

~~Very few additions where made, e.g. better formatting of tables. ~~

In the meantime some encodings bugs have been fixed. 🙂

python setup.py sdist bdist_wheel twine upload -r testpypi dist/* twine upload -r pypi dist/* 

About

Stripping rtf to plain old text

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

convert RTF format file to plain text file

gangcai/rtf2txt

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Convert RTF (Rich Text Format) format file to plain text file

python >2.7 Python packages: re glob os argparse sys 

RTF format file (see «example.rtf»)

python rtf2txt.py -i example.rtf

$ python rtf2txt.py -h usage: rtf2txt.py [-h] -i INPUT [-d OUTDIR] [-o OUTPUT] convert RTF format file to plain text file optional arguments: -h, --help show this help message and exit -i INPUT, --input INPUT input your RTF format file -d OUTDIR, --outdir OUTDIR the path to the output folder(default: ./ ) -o OUTPUT, --output OUTPUT text output file name (default: text.txt) before running, please install required python packages 

About

convert RTF format file to plain text file

Источник

Оцените статью