Chinaunix

标题: 求助,报错 [打印本页]

作者: tomer    时间: 2014-11-15 15:43
标题: 求助,报错
file.py:

  1. #!coding=utf-8
  2. #Author Tandaly
  3. #Date 2013-04-08
  4. #File PrintUnicode.py
  5. #引入相关包
  6. import sys
  7. import unicodedata

  8. #打印unicode
  9. def print_unicode(word):
  10.         titleList = ["decimal", "hex", "chr", "name"]   #标题列表
  11.         print("{0[0]:7}{0[1]:^5}{0[2]:>3}{0[3]:^40}".format(titleList)) #打印标题
  12.         print(("{0:-^"+ str(len(titleList[0])) +"}{0:-^5}{0:->"+ str(len(titleList[2])) +"}{0:-^40}").format(""))       #打印分隔线

  13.         code = ord(" ")         #decimal  将空格转换为十进制
  14.         end = sys.maxunicode    #取得系统内置最大unicode编码的十进制

  15.         while code < end:       #循环判断只要code小于最大unicode就执行操作
  16.                 name = unicodedata.name(chr(code), "***unknown***")     #根据unicode字符取得对应的unicode name
  17.                 if word is None or word in name.lower():        #如果word为None 或者word被包含于name中
  18.                         print("{0:>7}{0:>5X}{0:^3c}{1:<40}".format(code, name.title())) #打印unicode列表
  19.                 code += 1       #code增1

  20. if __name__ == "__main__":
  21.         word = None
  22.         argv = sys.argv
  23.         if len(argv) > 1:       #用户输入了命令行参数
  24.                 if argv[1] in ("-h", "--help"): #如果命令行参数中包含-h --help之类的词,说明用户要获得帮助说明
  25.                         print("usage: {0} [string]".format(argv[0]))
  26.                         word = 0
  27.                 else:   #取得命令行参数并最小化
  28.                         word = argv[1].lower()
  29.         else:   #命令行没有输入任何参数,就需要提示并让用户输入参数
  30.                 line = input("Please input a string:")  #提示输入参数
  31.                 if line is not None:    #如果参数不为空
  32.                         word = line.lower()     #参数进行最小化

  33.         if word != 0:   #如果word不为0,则是需要进行打印unicode操作
  34.                 print_unicode(word)     #调用定义的打印unicode操作
复制代码
执行:

  1. Please input a string:f
  2. decimal hex chr                  name                  
  3. -------------------------------------------------------
  4.      40   28 ( Left Parenthesis                        
  5.      46   2E . Full Stop                              
  6.      52   34 4 Digit Four                              
  7.      53   35 5 Digit Five                              
  8.      70   46 F Latin Capital Letter F                  
  9.      91   5B [ Left Square Bracket                     
  10.      94   5E ^ Circumflex Accent                       
  11.     102   66 f Latin Small Letter F                    
  12.     123   7B { Left Curly Bracket                     
  13. Traceback (most recent call last):
  14.   File "3.py", line 33, in <module>
  15.   File "3.py", line 16, in print_unicode
  16. UnicodeEncodeError: 'ascii' codec can't encode character '\xaa' in position 13: ordinal not in range(128)
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2