gpt4 book ai didi

python - 将unicode文本输出到python中的RTF文件

转载 作者:太空狗 更新时间:2023-10-30 03:06:01 25 4
gpt4 key购买 nike

我正在尝试从 python 脚本将 unicode 文本输出到 RTF 文件。对于背景,Wikipedia

For a Unicode escape the control word \u is used, followed by a 16-bit signed decimal integer giving the Unicode UTF-16 code unit number. For the benefit of programs without Unicode support, this must be followed by the nearest representation of this character in the specified code page. For example, \u1576? would give the Arabic letter bāʼ ب, specifying that older programs which do not have Unicode support should render it as a question mark instead.

还有this question on outputting RTF from Javathis one on doing so in C# .

但是,我无法弄清楚的是如何从 Python 将 unicode 代码点输出为“具有 Unicode UTF-16 代码单元编号的 16 位带符号十进制整数”。我试过这个:

for char in unicode_string:
print '\\' + 'u' + ord(char) + '?',

但在文字处理器中打开时,输出只会呈现为乱码;问题似乎是它不是 UTF-16 代码。但不确定如何获得它;虽然可以用 utf-16 编码,但如何获得代码编号?

顺便提一下,PyRTF 不支持 unicode(它被列为“待办事项”),虽然 pyrtf-NG 应该支持,但该项目似乎没有得到维护并且文档很少,所以我对使用它持谨慎态度在准生产系统中。

编辑:我的错误。上面的代码中有两个错误——正如 Wobble 在下面指出的那样,字符串必须是 unicode 字符串,而不是已经编码的字符串,并且上面的代码产生的结果是字符之间有空格。正确的代码是这样的:

convertstring=""
for char in unicode(<my_encoded_string>,'utf-8'):
convertstring = convertstring + '\\' + 'u' + str(ord(char)) + '?'

这工作正常,至少在 OpenOffice 中是这样。我把这个留在这里作为其他人的引用(一个错误在下面讨论后进一步更正)。

最佳答案

根据您最近编辑的信息,我认为该功能可以正常使用。除了看到下面的改进版本。

def rtf_encode(unistr):
return ''.join([c if ord(c) < 128 else u'\\u' + unicode(ord(c)) + u'?' for c in unistr])

>>> test_unicode = u'\xa92012'
>>> print test_unicode
©2012
>>> test_utf8 = test_unicode.encode('utf-8')
>>> print test_utf8
©2012
>>> print rtf_encode(test_utf8.decode('utf-8'))
\u169?2012

这是另一个版本,为了更容易理解,它被分解了一些。我还使它在返回 ASCII 字符串时保持一致,而不是保留 Unicode 并在 join 处乱用它。它还包含基于评论的修复。

def rtf_encode_char(unichar):
code = ord(unichar)
if code < 128:
return str(unichar)
return '\\u' + str(code if code <= 32767 else code-65536) + '?'

def rtf_encode(unistr):
return ''.join(rtf_encode_char(c) for c in unistr)

关于python - 将unicode文本输出到python中的RTF文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9908647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com