使用Python读取RTF文件时的欧元符号问题

arp*_*pho 2 python unicode rtf

我需要使用Python和pyRTF在RTF中生成一个文档,一切都很好:我对重音字母没有问题,它甚至接受欧元符号没有错误,但是我得到了这个符号:¤.我用这种方式编码字符串:

x.encode("iso-8859-15")
Run Code Online (Sandbox Code Playgroud)

我google了很多,但我无法解决这个问题,我需要做些什么来获得欧元符号?

Mar*_*ers 5

RTF标准使用UTF-16,但形状适合RTF命令序列格式.记录在http://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding.不幸的是,pyRTF没有为你做任何编码; 处理这个已经在项目的TODO上,但显然他们在放弃图书馆之前从未达到过这个目的.

这基于我最近在项目中使用的代码.我现在已经rtfunicode在PyPI上发布了这个,支持Python 2和3; python 2版本:

import codecs
import re

_charescape = re.compile(u'([\x00-\x1f\\\\{}\x80-\uffff])')
def _replace(match):
    codepoint = ord(match.group(1))
    # Convert codepoint into a signed integer, insert into escape sequence
    return '\\u%s?' % (codepoint if codepoint < 32768 else codepoint - 65536)    


def rtfunicode_encode(text, errors):
    # Encode to RTF \uDDDDD? signed 16 integers and replacement char
    return _charescape.sub(_replace, escaped).encode('ascii')


class Codec(codecs.Codec):
    def encode(self, input, errors='strict'):
        return rtfunicode_encode(input, errors), len(input)


class IncrementalEncoder(codecs.IncrementalEncoder):
    def encode(self, input, final=False):
        return rtfunicode_encode(input, self.errors)


class StreamWriter(Codec, codecs.StreamWriter):
    pass


def rtfunicode(name):
    if name == 'rtfunicode':
        return codecs.CodecInfo(
            name='rtfunicode',
            encode=Codec().encode,
            decode=Codec().decode,
            incrementalencoder=IncrementalEncoder,
            streamwriter=StreamWriter,
        )

codecs.register(rtfunicode)
Run Code Online (Sandbox Code Playgroud)

而不是编码为"iso-8859-15",然后您可以编码为'rtfunicode':

>>> u'\u20AC'.encode('rtfunicode') # EURO currency symbol
'\\u8364?'
Run Code Online (Sandbox Code Playgroud)

以这种方式将您插入RTF文档的任何文本编码.

注意它只支持UCS-2 unicode(\uxxxx,2个字节),而不支持UCS-4(\Uxxxxxxxx,4个字节); rtfunicode1.1通过简单地将UTF-16代理对编码为两个有\uDDDDD?符号整数来支持这些.