【问题标题】:Python unicode equal comparison failed in terminal but working under Spyder editorPython unicode 相等比较在终端中失败,但在 Spyder 编辑器下工作
【发布时间】:2014-06-04 10:13:43
【问题描述】:

我需要将来自 utf-8 文件的 unicode 字符串与 Python 脚本中定义的常量进行比较。

我在 Linux 上使用 Python 2.7.6。

如果我在 Spyder(一个 Python 编辑器)中运行上面的脚本,我可以让它工作,但是如果我从终端调用 Python 脚本,我的测试就会失败。在调用脚本之前,我是否需要在终端中导入/定义某些内容?

脚本(“pythonscript.py”):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv

some_french_deps = []
idata_raw = csv.DictReader(open("utf8_encoded_data.csv", 'rb'), delimiter=";")
for rec in idata_raw:
    depname = unicode(rec['DEP'],'utf-8')
    some_french_deps.append(depname)

test1 = "Tarn"
test2 = "Rhône-Alpes"
if test1==some_french_deps[0]:
  print "Tarn test passed"
else:
  print "Tarn test failed"
if test2==some_french_deps[2]:
  print "Rhône-Alpes test passed"
else:
  print "Rhône-Alpes test failed"

utf8_encoded_data.csv:

DEP
Tarn
Lozère
Rhône-Alpes
Aude

从 Spyder 编辑器运行输出:

Tarn test passed
Rhône-Alpes test passed

从终端运行输出:

$ ./pythonscript.py 
Tarn test passed
./pythonscript.py:20: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  if test2==some_french_deps[2]:
Rhône-Alpes test failed

【问题讨论】:

  • 呸,Spyder 做了所有的事情来破坏 Python 环境的正常运行。在这种情况下,我强烈怀疑默认的隐式转换编码已更改。
  • locale 从 bash 中显示什么?
  • @PadraicCunningham:语言环境对 Python 如何在 Unicode 和字节字符串之间进行强制转换没有影响。
  • @MartijnPieters,是的,我最初误解了这个问题。如果已经声明了编码,我认为没有必要使用 u"Tarn",只是比较应该可以工作还是我遗漏了什么?
  • @PadraicCunningham:编解码器只告诉 Python 如何解释换行符以及如何解码 Unicode 文字的字节。声明编解码器时,字节字符串文字不会自动解码为 Unicode 值,不。

标签: python unicode utf-8 spyder


【解决方案1】:

您正在将字节字符串(类型 str)与 unicode 值进行比较。 Spyder 已更改默认编码从 ASCII 到 UTF-8,当比较这两种类型时,Python 会在字节字符串和 unicode 值之间进行隐式转换。您的字节字符串被​​编码为 UTF-8,因此在 Spyder 下比较成功。

解决方案是使用字节字符串,而是使用unicode 文字作为您的两个测试值:

test1 = u"Tarn"
test2 = u"Rhône-Alpes"

在我看来,更改系统默认编码是一个糟糕的主意。你的代码应该正确使用 Unicode 而不是依赖隐式转换,但是改变隐式转换的规则只会增加混乱,不会让任务变得更容易。

【讨论】:

    【解决方案2】:

    只使用depname = rec['DEP'] 应该可以工作,因为您已经声明了编码。

    如果您print some_french_deps[2],它将打印Rhône-Alpes,因此您的比较将起作用。

    【讨论】:

      【解决方案3】:

      当您将字符串对象与 unicode 对象进行比较时,python 会抛出此警告。

      要解决这个问题,你可以写

      test1 = "Tarn"
      test2 = "Rhône-Alpes"
      

      作为

      test1 = u"Tarn"
      test2 = u"Rhône-Alpes"
      

      “u”表示它是一个 unicode 对象。

      【讨论】:

        猜你喜欢
        • 2013-08-14
        • 1970-01-01
        • 2012-06-03
        • 2017-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-06
        • 2013-12-08
        相关资源
        最近更新 更多