python 从 .rtf 文件读取时添加乱码?

发布于 2024-08-07 15:55:27 字数 484 浏览 1 评论 0原文

我有一个 .rtf 文件,只包含一个整数,比如 15。我希望通过 python 读取这个整数并以某种方式操作该整数。然而,Python 似乎正在读取与 .rtf 文件相关的大部分元数据。这是为什么?我怎样才能避免它?例如,尝试读取此文件,我得到..

{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460 {\fonttbl\f0\fswiss\fcharset0 黑体;} {\colortbl;\red255\green255\blue255;} \margl720\margr720\margb720\margt720\vieww9000\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural

I have a .rtf file that contains nothing but an integer, say 15. I wish to read this integer in through python and manipulate that integer in some way. However, it seems that python is reading in much of the metadata associated with .rtf files. Why is that? How can I avoid it? For example, trying to read in this file, I get..

{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf460
{\fonttbl\f0\fswiss\fcharset0
Helvetica;}
{\colortbl;\red255\green255\blue255;}
\margl720\margr720\margb720\margt720\vieww9000\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还在原地等你 2024-08-14 15:55:27

这就是 .RTF(即富文本文件)的本质,它们包含额外的数据来定义文本的布局和格式。

不建议将数据存储在此类文件中,以免遇到您提到的困难。您是否会努力解析此文件并“恢复”您的一个数值,您的应用程序可能会面临 RTF 格式更新版本的风险,这可能会导致解析逻辑部分不正确,从而产生错误的数值数据应用)。

为什么不将此信息存储在真正的文本文件中。这可以是纯文本文件,或者最好是 XML、YAML、JSON 文件,例如,为了添加应用程序的“前向”兼容性,您可以在文件中添加额外的参数等。

但是,如果给定此文件,则可能存在可对其进行读写的 Python 库。检查 Python 包索引 (PyPI) 中的 RTF 关键字。

That's the nature of .RTF (i.e Rich Text files), they include extra data to define how the text is layed-out and formated.

It is not recommended to store data in such files lest you encounter the difficulties you noted. Would you go through the effort to parse this file and "recover" your one numeric value, you may expose your application to the risk of updated versions of the RTF format which may render the parsing logic partially incorrect and hence yield wrong numeric data for the application).

Why not store this info in a true text file. This could be a flat text file or preferably an XML, YAML, JSON file for example for added "forward" compatibility as your application and you may add extra parameters and such in the file.

If this file is a given, however, there probably exist Python libraries to read and write to it. Check the Python Package Index (PyPI) for the RTF keyword.

柠檬色的秋千 2024-08-14 15:55:27

这正是 RTF 文件包含的内容,因此 Python(在没有进一步说明的情况下)会为您提供该文件包含的内容。

您可能正在寻找一个库来读取 RTF 文件的内容,例如 pyrtf-ng

That's exactly what the RTF file contains, so Python (in the absence of further instruction) is giving you what the file contains.

You may be looking for a library to read the contents of RTF files, such as pyrtf-ng.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文