【问题标题】:Convert a unicode string to its original format [duplicate]将unicode字符串转换为其原始格式[重复]
【发布时间】:2012-05-25 11:02:49
【问题描述】:

可能重复:
Converting a latin string to unicode in python

存储在文件中后,我有一个具有以下格式的列表

list_example = [
         u"\u00cdndia, Tail\u00e2ndia & Cingapura",
         u"Lines through the days 1 (Arabic) \u0633\u0637\u0648\u0631 \u0639\u0628\u0631 \u0627\u0644\u0623\u064a\u0627\u0645 1",
]

但列表中字符串的实际格式是

actual_format = [
         "Índia, Tailândia & Cingapura ",
         "Lines through the days 1 (Arabic) سطور عبر الأيام 1 | شمس الدين خ "
]

如何将list_example 中的字符串转换为actual_format 列表中的字符串?

【问题讨论】:

  • 格式已经对了...试试print list_example[1]
  • 注意:您需要 .encode() list_example[1] 到您的终端可以理解的编码,具体取决于您的区域设置。
  • 但是我在尝试时遇到了以下错误
  • [i.decode('unicode-escape') for i in list_example]
  • "UnicodeEncodeError: 'ascii' codec can't encode character u'\xcd' in position 0: ordinal not in range(128)"

标签: python list unicode-string


【解决方案1】:

你的问题对我来说有点不清楚。无论如何,以下指南应该可以帮助您解决问题。

如果你在 Python 源代码中定义了这些字符串,那么你应该

  • 知道您的编辑器以哪种字符编码保存源代码文件(例如 utf-8)
  • 在源文件的第一行声明该编码,例如通过# -*- coding: utf-8 -*-
  • 将这些字符串定义为 unicode 对象:

strings = [u"Índia, Tailândia & Cingapura ", u"Lines through the days 1 (Arabic) سطور عبر الأيام 1 | شمس الدين خ "]

(注意:在 Python 3 中,文字字符串默认为 unicode 对象,即您不需要 u。在 Python 2 中,unicode 字符串的类型为 unicode,在 Python 3 中,unicode 字符串的类型为输入string。)

当您想要将这些字符串保存到文件中时,您应该明确定义字符编码:

with open('filename', 'w') as f:
    s = '\n'.join(strings)
    f.write(s.encode('utf-8'))

当您想再次从该文件中读取这些字符串时,您必须再次明确定义字符编码才能正确解码文件内容:

with open('filename') as f:
    strings = [l.decode('utf-8') for line in f]

【讨论】:

  • 如果涉及 unicode,您应该使用 codecs 模块写入/读取文件。例如with codecs.open('test', encoding='utf-8', mode='w')。有关详细信息,请参阅 Unicode HOWTO:docs.python.org/howto/unicode.html
  • 是的,这是一个非常方便的模块。但是,我回答的目的是让 shiva 掌握编码/解码要领。因此,我不会修改答案,好吗? :)
【解决方案2】:
actual_format = [x.decode('unicode-escape') for x in list_example]

【讨论】:

  • 但是当我运行上述命令时,我收到以下错误“UnicodeEncodeError: 'ascii' codec can't encode character u'\xcd' in position 0: ordinal not in range(128)”
猜你喜欢
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2019-11-30
  • 1970-01-01
  • 2014-01-07
  • 2020-06-26
相关资源
最近更新 更多