您需要知道文件以哪种编码保存。就像“ utf-8”(不是Unicode)或“ iso-8859-1”或“ cp1252”之类。
然后,您可以做(假设’utf-8’):
infile = open(sys.argv[1])
for line in infile:
print line,
domain = line.strip().decode('utf-8')
print type(domain)
print "IDN:", domain.encode("idna")
print
使用将编码后的字符串转换为unicodedecode
。使用将Unicode转换为字符串encode
。如果您尝试对已经编码的内容进行编码,则python会首先尝试使用默认编解码器“ ascii”(对于非ASCII值)失败进行解码。