rtf文件的字符编码错误

问题描述 投票:2回答:1

当我将句子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的原因是能够导出带有颜色编码的单词的句子,允许手动编辑它们,然后再读回来进行进一步处理)。

python character-encoding rtf
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.