【发布时间】: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