如何在列表表示中打印国家字符?

时间:2013-10-02 13:27:46

标签: python json unicode utf-8

我正在用特殊字符(å,ä,ö)编写JSON数据到文件然后再读回来。然后我在子进程命令中使用这些数据。使用读取数据时,我无法将特殊字符分别转换回å,ä和ö。

当运行下面的python脚本时,列表“command”打印为:

['cmd.exe', '-Name=M\xc3\xb6tley', '-Bike=H\xc3\xa4rley', '-Chef=B\xc3\xb6rk']

但我希望它像这样打印:

['cmd.exe', '-Name=Mötley', '-Bike=Härley', '-Chef=Börk']

Python脚本:

# -*- coding: utf-8 -*-

import os, json, codecs, subprocess, sys


def loadJson(filename):
    with open(filename, 'r') as input:
        data = json.load(input)
    print 'Read json from: ' + filename
    return data

def writeJson(filename, data):
    with open(filename, 'w') as output:
        json.dump(data, output, sort_keys=True, indent=4, separators=(',', ': '))
    print 'Wrote json to: ' + filename



# Write JSON file
filename = os.path.join( os.path.dirname(__file__) , 'test.json' )
data = { "Name" : "Mötley", "Bike" : "Härley", "Chef" : "Börk" }
writeJson(filename, data)


# Load JSON data
loadedData = loadJson(filename)


# Build command
command = [ 'cmd.exe' ]

# Append arguments to command
arguments = []
arguments.append('-Name=' + loadedData['Name'] )
arguments.append('-Bike=' + loadedData['Bike'] )
arguments.append('-Chef=' + loadedData['Chef'] )
for arg in arguments:
    command.append(arg.encode('utf-8'))

# Print command (my problem; these do not contain the special characters)
print command

# Execute command
p = subprocess.Popen( command , stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# Read stdout and print each new line
sys.stdout.flush()
for line in iter(p.stdout.readline, b''):
    sys.stdout.flush()
    print(">>> " + line.rstrip())

1 个答案:

答案 0 :(得分:3)

这是Python中字符串常量的规范表示,旨在消除编码问题。实际上,它是字符串返回的repr()。 List的str()函数实现在其成员打印时调用repr()来表示它们。

输出具有非ASCII字符的字符串的唯一方法是print或以其他方式将其写入流。有关打印时字符转换的方式,请参阅Why does Python print unicode characters when the default encoding is ASCII?。另请注意,对于非ASCII 8位字符,对于为不同代码页设置的终端,输出将不同。

关于解决方案:

最简单的方法是制作替代str(list)实施方案,该方案将调用str()而不是repr() - 注意上述警告。

def list_nativechars(l):
  assert isinstance(l,list)
  return "[" + ", ".join('"'+str(i)+'"' for i in l) + "]"

现在(在cp866控制台编码中):

>>> l=["йцукен"]
>>> print list_nativechars(l)
["йцукен"]

使用外国编码的数据:

# encoding: cp858
<...>
l= ['cmd.exe', '-Name=Mötley', '-Bike=Härley', '-Chef=Börk']
print list_nativechars(l)

c:\>python t.py
["cmd.exe", "-Name=MФtley", "-Bike=HДrley", "-Chef=BФrk"]
相关问题