lshboo 发表于 2018-8-15 10:37:55

python处理中文字符

  python里面默认的字符串都是ASCII编码,是string类型,ASCII编码处理中文字符是会出问题的。
  python的内部编码格式是unicode,在字符串前加‘u’前缀也可直接声明unicode字符串,如 u'hello'就是unicode类型。
  如果处理的字符串中出现非ascii码表示的字符,要想不出错,就得转成unicode编码了。具体的方法有:
  decode(),将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码;
  encode(),将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码;
  unicode(),同decode(),将其他编码的字符串转换成unicode编码,如unicode(str3, 'gb2312'),表示将gb2312编码的字符串str3转换成unicode编码。
  转码的时候一定要先搞明白字符串str是什么编码,然后decode成unicode,最后再encode成其他编码。
  另外,对一个unicode编码的字符串在进行解码会出错,所以在编码未知的情况下要先判断其编码方式是
  否为unicode,可以用isinstance(str, unicode)。
  不仅是中文,以后处理含非ascii编码的字符串时,都可以遵循以下步骤:
  1、确定源字符的编码格式,假设是utf8;
  2、使用unicode()或decode()转换成unicode编码,如str1.decode('utf8'),或者unicode(str1, 'utf8');
  3、把处理后字符串用encode()编码成指定格式。
  #!/usr/bin/env python
  #-*- coding:utf-8 -*-
  import sys, os
  import md5
  destPath = r'h:\路径A\测试'
  srcPath = r'h:\路径B\测试'
  rstPath = r'h:\路径C\rst.txt'
  #----------------------------------------------------------------------
  def find_all_files(path):
  '''''
  '''
  print '\r\r'
  files = os.listdir(path.decode('utf8'))
  fileslist = []
  for ff in files:
  ffPath = path + '\\' + ff
  print ffPath,
  if os.path.isfile(ffPath):
  fileslist.append(ffPath)
  print 'file'
  elif os.path.isdir(ffPath):
  print 'dir'
  fileslist += find_all_files(ffPath)
  else:
  print 'parse error!', '\t', ffPath
  return fileslist
  #----------------------------------------------------------------------
  def md5_list(path):
  '''''
  '''
  filesList = find_all_files(path)
  filesMd5 = {}
  for ff in filesList:
  try:
  fp = open(ff, 'rb')
  m = md5.md5()
  strRead = ""
  while True:
  strRead = fp.read(8096)
  if not strRead:
  break
  m.update(strRead)
  strMd5 = m.hexdigest()
  filesMd5 = ff
  fp.close()
  except Exception, ex:
  print ex
  fp.close()
  return filesMd5
  if __name__=='__main__':

  >  sys.setdefaultencoding('utf-8')
  print 'Begin.......'
  srcFilesMd5 = md5_list(srcPath)
  destFilesMd5 = md5_list(destPath)
  rst = ''
  for key in srcFilesMd5.keys():
  if key not in destFilesMd5.keys():
  fileName = srcFilesMd5
  rst = rst + fileName.encode('utf8') + '\r'
  fp = open(rstPath, 'w')
  fp.write(rst)
  fp.close()
  print '\nRun Over......'
页: [1]
查看完整版本: python处理中文字符