【问题标题】:How to print national characters in list representation?如何在列表表示中打印国家字符?
【发布时间】:2013-10-02 13:27:45
【问题描述】:

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

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

['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())

【问题讨论】:

  • 打印列表中的字符串而不是列表,特殊字符会神奇地重新出现
  • M\xc3\xb6tley Mötley,用utf8编码,就像你写的那样。你的代码很好。
  • @hop - 这样打印列表只是为了说明这些值不包含 åöä 字符。它在 subprocess.Popen 中,我遇到了真正的问题,因为参数不包含 åöä 字符。
  • Unicode in python 的可能重复项
  • @fredrik:a) 你错了。 b)您的问题可能是Windows。 c) 你确定 cmd.exe 可以处理 utf-8 吗?

标签: python json unicode utf-8


【解决方案1】:

这是 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"]

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 2014-12-19
    • 1970-01-01
    • 2022-11-04
    • 2022-08-22
    • 2013-02-27
    • 2014-01-23
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多