python读取rtf文件_使用Python读取RTF文件时出现欧元符号问题

RTF标准使用UTF-16,但其形状适合RTF命令序列格式。记录在http://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding。不幸的是,pyRTF不为您进行任何编码;处理这一点已经在项目的TODO中完成了,但是很明显,他们在放弃库之前从来没有做到这一点。在

这是基于我最近在一个项目中使用的代码。我现在将其发布为^{} on PyPI,支持Python2和3;Python2版本: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)

而不是编码为“iso-8859-15”,您可以编码为“rtfunicode”:

^{pr2}$

以这种方式对插入到RTF文档中的任何文本进行编码。在

注意,它只支持UCS-2unicode(\uxxxx,2个字节),不支持UCS-4(\Uxxxxxxxx,4个字节);rtfunicode1.1只支持将UTF-16代理项对编码为两个\uDDDDD?有符号整数。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值