【问题标题】:Printing unicode string works in python 3.2 but not in 2.7打印 unicode 字符串在 python 3.2 中有效,但在 2.7 中无效
【发布时间】:2012-08-30 13:33:13
【问题描述】:

我使用 Python 3.2 处理带有 utf-8 文本的文本文件:

import codecs
import csv
f = codecs.open('07362853300091_trade_turquoise_errNo_031.csv', 
                                         'r','utf-8', 'ignore')
text = csv.reader(f, delimiter=',', quotechar='"')
for row in text:
    for item in row:
        print(item)

工作正常。

我现在必须使用 Python 2.7 解释器运行代码并打印:

'\xd7\x97\xd7\x99\xd7\x95\xd7\x91\xd7\x94\xd7\xa8\xd7\xa2\xd7\xa6\xd7\x99\xd7\x95\xd7\x9f'

我试过了

item.encode('utf-8')
print unicode(item, errors='ignore')

(还尝试了其他一些 encode() 和 unicode() 函数的组合),它总是打印:

你'\u05de\u05e9\u05d9\u05db\u05ea \u05e9\u05d9\u05e7'

如何在 Python 2.7 中将 unicode 文本打印到控制台?

【问题讨论】:

  • Unicode 字符串看起来是正确的;这是 'חיוב הר עציון' 的转义表示。
  • type(item)item.encode('utf-8') 之前和之后是什么?我猜item 是一个unicode 对象。编码后,它是 Python 2.7 中的 str 对象。只需打印此内容,无需使用unicode() 进行后续转换。

标签: python unicode


【解决方案1】:

the docs 中查看unicode_csv_reader()

如果控制台理解 utf-8 并且除了将项目打印到控制台之外,您不对项目进行任何文本处理,您也可以跳过解码/编码:

with open('07362853300091_trade_turquoise_errNo_031.csv', 'rb') as file:
     for row in csv.reader(file):
         print "\n".join(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2013-11-23
    • 1970-01-01
    相关资源
    最近更新 更多