【问题标题】:problems with handling unicode characters in python在 python 中处理 unicode 字符的问题
【发布时间】:2012-04-26 16:06:20
【问题描述】:

我写了下面的代码来将内容写入文件,

   with codecs.open(name,"a","utf8") as myfile:
         myfile.write(str(eachrecord[1]).encode('utf8'))
         myfile.write(" ")
         myfile.write(str(eachrecord[0]).encode('utf8'))
         myfile.write("\n")`

上面的代码在编写 uni-code 字符时不能正常工作......即使我正在使用编解码器并进行编码。我不断收到错误

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 6: ordinal not in range(128)

谁能看出我哪里做错了?

编辑:

with codecs.open(name,"a","utf8") as myfile:
                    myfile.write(unicode(eachrecord[1]))
                    myfile.write(" ")
                    myfile.write(unicode(eachrecord[0]))
                    myfile.write("\n")

这行得通..感谢所有快速的 cmets 和答案..这真的很有帮助..直到你们告诉我,我才意识到 python 有 'unicode' 选项

【问题讨论】:

  • eachrecord[1] 是什么类型?我猜str 弄得一团糟,请改用unicode
  • 而且我认为您甚至不必对 unicode 字符串进行编码,因为使用编解码器打开的文件应该可以处理它。
  • 每个记录[1] 可以是字符串或数字
  • TypeError: coercing to Unicode: need string or buffer, int found..关于如何解决这个问题的任何建议

标签: python unicode


【解决方案1】:

删除str() 调用。他们正在使用默认编码(在这种情况下为ascii)进行隐式编码。

【讨论】:

  • 谢谢,当我删除 str() 调用时,我不断收到此错误“AttributeError: 'int' object has no attribute 'encode'”
猜你喜欢
  • 2019-09-04
  • 2021-12-02
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 2010-12-11
相关资源
最近更新 更多