【问题标题】:python encoding problem when writing to rtf写入rtf时的python编码问题
【发布时间】:2020-01-04 04:45:02
【问题描述】:

我正在使用 python3 并使用 python 写入 rtf 文件,但是在使用 char ø(也称为“\u00f8”)时会出现一些编码问题。 这是代码:

>>> myText = "a \u00f8 b"
>>> myText
'a ø b'

>>> out_file = open('test.rtf', 'w', encoding='utf8')
>>> textForFile = "{\\rtf1\\utf8 " + myText + "}"

>>> out_file.write(textForFile)
18
>>> out_file.close()

文件 test.rtf 现在包含以下文本:

a ˆ‚ b

代替:

'a ø b'

知道我在编码中缺少什么吗?

【问题讨论】:

  • 我认为问题在于您是否以 utf-8 格式打开此文件?我是说你的编辑。
  • 是的,我在 Mac 上使用 TextEdit 打开它,根据 Preferences 它使用的是 utf-8 编码
  • @DevB2F 删除encoding='utf8' 并尝试。我在 Windows 中试过这个,当我打开 .rtf 文件时,它显示 a ø b。当我使用encoding='utf8' 时,它显示a ø b
  • @DevB2F 你安装了 MS word 吗?尝试使用 MS Word。如果它仍然没有显示预期的输出,那么我们可以将其标记为 macos TextEdit 问题。
  • 我用 utf-8 编码通过 sublime 打开这个文件,它可以工作。

标签: python python-3.x utf-8 rtf


【解决方案1】:

解决问题的关键是使用 cp1252 对 python 文件进行编码,并在 rtf 代码中使用 ansicpg1252。我找到了 ansicpg1252 的想法in this documentation。现在 TextEdit、LibreOffice 和 OpenOffice 都可以正确打开文件了。

正确代码:

>>> myText = "a \u00f8 b"
>>> myText
'a ø b'
>>> out_file = open('test.rtf', 'w', encoding='cp1252')
>>> textForFile = "{\\rtf1\\ansicpg1252" + myText + "}"
>>> out_file.write(textForFile)
>>> out_file.close()

【讨论】:

    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多