【问题标题】:Python. Convert escaped utf string to utf-stringPython。将转义的 utf 字符串转换为 utf 字符串
【发布时间】:2017-03-02 06:33:36
【问题描述】:

有没有内置的方法可以做到这一点?

rawstr = r"3 \u176? \u177? 0.2\u176? (2\u952?)"
#required str is 3 ° ± 0.2° (2θ).

类似

In [1] rawstr.unescape()?
Out[1]: '3° ± 0.2° 2θ'

问题是如何将 rawstr 转换为 'utf-8'。

请看我的回答更清楚。

如果比我现在做的更好,请回答。

【问题讨论】:

  • 你可以使用codecs.raw_unicode_escape_decode。不幸的是,您的原始字符串包含无效的 unicode 转义,因此它不起作用(我指的是\u176?。它们应该采用\uXXXX 的形式)
  • 或者,创建一个字节串(使用rb 作为前缀)并使用.decode('unicode-escape'),但这再次失败,因为\u176? 不是有效的Unicode 转义。
  • 谢谢。我想我必须为我编写解码器。

标签: python


【解决方案1】:

是的,有!

对于python 2:

print r'your string'.decode('string_escape')

对于python 3,需要将其转换为字节,然后使用decode

print(rb'your string'.decode('unicode_escape'))

请注意,这在您的情况下不起作用,因为您的符号没有正确转义(即使您使用“正常”方式打印它们,它也不起作用)。


你的字符串应该是这样的:

rb'3\u00B0 \u00b1 0.2\u00B0 2\u03B8'

注意,如果需要在python中将string转换为bytes,可以使用bytes函数。

my_str = r'3\u00B0 \u00b1 0.2\u00B0 2\u03B8'
my_bytes = bytes(my_str, 'utf-8')
print my_bytes.decode('string_escape') # python 2
print(my_bytes.decode('unicode_escape')) # python 3

【讨论】:

  • 我认为是ansi文本。
  • “ANSI 文本”不是一个定义明确的术语。在 Windows 上,它在过去被误导性地用来指代系统的本地默认编码,这被广泛地进一步误解为特定的代码页(通常是 1252,尽管您会看到所有 437、850,以及在读者的语言环境)。
【解决方案2】:

如果你在 windows 上并安装了 pythonnet

import clr
clr.AddReference("System")
clr.AddReference("System.Windows.Forms")
import System.Windows.Forms as WinForms

def rtf_to_text(rtf_str):
    """Converts rtf to text"""

    rtf = r"{\rtf1\ansi\ansicpg1252" + '\n' + rtf_str + '\n' + '}'
    richTextBox = WinForms.RichTextBox()
    richTextBox.Rtf = rtf
    return richTextBox.Text

print(rtf_to_text(r'3 \u176? \u177? 0.2\u176? (2\u952?)'))
-->'3 ° ± 0.2° (2θ)'

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2010-09-21
    • 2014-02-05
    相关资源
    最近更新 更多