如何在列表表示中打印国家字符? [英] How to print national characters in list representation?
问题描述
我正在将带有特殊字符(å,ä,ö)的JSON数据写入文件,然后将其读回.然后在子处理命令中使用此数据.使用读取的数据时,我无法使特殊字符分别转换回å,ä和ö.
I'm writing JSON data with special characters (å, ä, ö) to file and then reading it back in. Then I use this data in a subprocess command. When using the read data I cannot make special characters get translated back to å, ä and ö respectively.
运行以下python脚本时,列表命令"显示为:
When running the python script below, the list "command" is printed as:
['cmd.exe', '-Name=M\xc3\xb6tley', '-Bike=H\xc3\xa4rley', '-Chef=B\xc3\xb6rk']
但是我希望它像这样打印:
But I want it to be printed like this:
['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())
推荐答案
这是Python中字符串常量的规范表示,旨在消除编码问题.实际上,这是字符串上的repr()
返回的内容. List的str()
函数实现在打印时调用,在其成员上调用repr()
表示它们.
This is the canonical representation of string constants in Python which is designed to eliminate encoding issues. Actually, it's what repr()
on a string returns. List's str()
function implementation that is called when it's printed calls repr()
on its members to represent them.
输出具有非ASCII字符的字符串的唯一方法是print
或将其写入流中.请参阅为什么使用Python默认编码为ASCII时会打印unicode字符吗?有关在打印时如何进行字符转换.另外请注意,对于非ASCII 8位字符,为不同代码页设置的终端的输出将有所不同.
The only way to output a string with non-ASCII characters as they are is to print
it or otherwise write it to a stream. See Why does Python print unicode characters when the default encoding is ASCII? on how character conversion is done on printing. Also note that for non-ASCII 8-bit characters, the output will be different for terminals set up for different codepages.
关于解决方案:
最简单的方法是制作一个替代的str(list)
实现,该实现将调用str()
而不是repr()
-注意上面的警告.
The simplest one will be to make an alternative str(list)
implementation that will call str()
instead of repr()
- noting the warnings above.
def list_nativechars(l):
assert isinstance(l,list)
return "[" + ", ".join('"'+str(i)+'"' for i in l) + "]"
现在(在cp866
控制台编码中):
Now (in cp866
console encoding):
>>> 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"]
这篇关于如何在列表表示中打印国家字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!