【问题标题】:How to Use unicode with a list or a string in Python如何在 Python 中将 unicode 与列表或字符串一起使用
【发布时间】:2013-07-16 14:46:24
【问题描述】:

所以我有一个我想使用 unicode 的爱尔兰(盖尔语单词)单词的列表,以便 RDFlib 能够理解单词中某些字母上方的重​​音。我不知道是在单词在列表中之前还是之后使用 unicode。这是我到目前为止的代码:

文件中的示例行 = 00001740 n 3 eintiteas aonán beith 003 ~ 00001930 n 0000

def process_file(self):
    self.file = open("testing_line_ir.txt", "r")
    return self.file

def line_for_loop(self, file):
    for line in file:
        self.myline = unicode(line, 'utf-8')
        for line in self.myline:
        ............here is where other processes are ran.......

这是给出错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xe1 in position 26: invalid continuation byte

我也试过这个:

def get_words_list(self, word_part, num_words):
    self.word = word_part[3:3 + num_words:1]
    self.myword = [unicode(i) for i in self.word]
    return self.myword

在这种情况下,'word' 是单词列表 ['eintiteas', 'aonán', 'beith'] 我尝试使用 myword 作为编码列表,但错误与上述相同。

编辑: 这是发生错误的源代码,它发生在 graph.parse 行 像 block1 和命名空间一样通过的变量只是文本行

def compose_printout(self, namespaces, block1, block2, close_rdf):
    self.printout += namespaces + block1 + block2 + close_rdf
    self.tabfile = StringIO(self.printout)
    return self.tabfile

def serialize(self, graph, tabfile):
    """ This will serialize with RDFLib """
    graph.parse(tabfile, publicID=None, format="xml")

其中一些词被添加到 RDFlib 图表中,所以这里的任何帮助都会很棒!

【问题讨论】:

  • 您的输入数据不是 UTF-8 编码。您需要找到用于文件数据的正确编解码器。

标签: python list unicode rdf


【解决方案1】:

您没有 UTF-8 数据。从异常消息中,我会说您使用的是 Latin-1 编码数据:

>>> print '\xe1'.decode('latin1')
á

您可以使用codecs.open() function 创建一个文件对象,该对象返回已解码的文件数据:

import codecs

def process_file(self):
    self.file = codecs.open("testing_line_ir.txt", "r", 'latin-1')
    return self.file

def line_for_loop(self, file):
    for line in file:
        # line is *already* unicode

【讨论】:

  • 现在收到此错误:UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 331: ordinal not in range(128)
  • @Johnnerz:您在某处混合了 unicode 和字节字符串值。不要那样做,类型之间的隐式强制以丑陋的方式失败。
  • 我怎样才能知道我在哪里做这个?这对我来说完全陌生,我两个月前才开始使用 python!
  • @Johnnerz:很难说,没有你的源代码。回溯告诉您异常被触发的位置(所以 before UnicodeEncodeError 行)。
  • @Johnnerz:但一般来说:UnicodeEncodeError 意味着使用 ASCII 编解码器(强制转换时 Python 默认设置)触发了从 Unicode 到字节字符串的转换。可能是您尝试将数据写入文件而不首先对其进行编码(它在您的值上调用 str(),尝试使用默认值对其进行编码等)。
【解决方案2】:

你可以在你的文件头上试试这些代码

import sys
reload(sys)
sys.setdefaultencoding('utf8')

【讨论】:

  • 这是一个坏主意,原因有很多。更改用于 Python 字符串强制的默认编码不是解决方案。真正的解决方案是在需要的地方显式编码或解码。
  • 此外,OP已经尝试显式解码,但使用了错误的编解码器。将默认编码设置为 UTF-8 有何帮助?
猜你喜欢
  • 1970-01-01
  • 2011-11-25
  • 1970-01-01
  • 2012-05-25
  • 1970-01-01
  • 2021-02-16
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多