首页 > 解决方案 > rtf文件的字符编码错误

问题描述

当我将句子复制并粘贴How brave they’ll all think me at home!到 Mac 上的空白 TextEdit rtf 文档中时,它看起来很好。但是,如果我以编程方式创建一个明显相同的 rtf 文件,并将相同的句子写入其中,在打开 TextEdit 时,它会显示为How brave they’ll all think me at home! 在以下代码output中,没问题,但是在 TextEdit 中查看文件时,右单引号 (这里用作撇号),unicode U-2019。

header = r"""{\rtf1\ansi\ansicpg1252\cocoartf1671\cocoasubrtf400
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
\f0\fs24 \cf0 """

sen = 'How brave they’ll all think me at home!'

with open('staging.rtf', 'w+’) as f:
    f.write(header)
    f.write(sen)
    f.write('}')

with open('staging.rtf') as f:
    output = f.read()
print(output)

我从https://www.i18nqa.com/debug/utf8-debug.html发现这可能是由“UTF-8 字节被解释为 Windows-1252”引起的,这似乎是有道理ansicpg1252的标题表示美国 Windows。

但是我仍然不知道如何解决它,即使在这里阅读了类似的问题:Encoding of rtf file。我试过用ansi无效替换mac。并且添加,encoding='utf8'到 open 函数似乎也无济于事。

(顺便说一句,使用 rtf 的原因是能够导出带有颜色编码的单词的句子,允许它们被手动编辑,然后读回以进行进一步处理)。

标签: pythoncharacter-encodingrtf

解决方案


好的,我自己找到了答案。, encoding='windows-1252'在写入 rtf 文件和读取文件时,我都需要使用它们。


推荐阅读