在Python中将重音字符写入rtf

时间:2014-05-30 13:51:53

标签: python unicode rtf

我正在尝试用rtf文件写入大量法语信息,包含重音字符。首先,我尝试使用编解码器写入文件:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import codecs

output = codecs.open("test.rtf", "w", 'utf-8')
name = unicode("Lumière", 'utf-8')

# This is just the rtf header 
# The whole point of using rtf is so that I can embed links
output.write("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{" + 
    "\\fonttbl{\\f0\\fnil\\fcharset0 Calibri;}}\\n{\\colortbl ;" + 
    "\\red0\\green0\\blue255;}\n{\\*\\generator Msftedit 5.41.21.2509;}" + 
    "\\viewkind4\\uc1\\pard\\sa200\\sl276\\slmult1\\lang9\\f0\\fs22\n\n")

output.write(name)

output.write("}")
output.close()

这会输出一个* .rtf文件,该文件显示为:

Lumière

textEdit和MS word中都有。在纯文本编辑器中将其作为文本文档打开,我们得到:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}\n{\colortbl ;\red0\green0\blue255;}
{\*\generator Msftedit 5.41.21.2509;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22

Lumière}

标题的gobbledeegook和正确格式化的单词。如果我直接编辑rtf文档,要添加è字符,源将更改为:

Lumi\'e8re

非常类似于:

>>> name = unicode("Lumière", 'utf-8')
>>> name
u'Lumi\xe8re'

这显然是我需要写入文件,但是将'x'换成撇号。如果我尝试编写没有编码(不要使用编解码器来打开文件),我会得到着名的

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 4: ordinal not in range(128)

错误。如何让file.write()停止尝试编码,我想字面写'\ xe8'而不是字符'\ xe8'表示文件(除了我想交换'x'表示撇号)。

0 个答案:

没有答案
相关问题