免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3675 | 回复: 1

用Python快速解决了遇到的一个问题,大家来看看 [复制链接]

论坛徽章:
0
发表于 2005-06-08 16:14 |显示全部楼层
Written by wolfg

问题:申请了一个免费Wiki空间,有备份功能,但保存下来的zip文件里的中文文件名和内容都是乱码,如图



分析:解压缩后,用UltraEdit打开乱码的文件,发现转换成UTF-8后可以正常显示中文

解决思路:写一个Python脚本,解压缩,把UTF-8编码的文件名和文件内容转成GBK编码。

google后在ASPN上找到的一个解压缩zip文件的例子http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252508,为了在下面的convert.py脚本里使用,改了一下extract方法,返回zip文件的文件列表。

convert.py先把压缩文件解开,然后读取每个文件,用utf-8编码读取,然后用gbk写入另一个文件

  1. """ unzip.py
  2.     Version: 1.1

  3.     Extract a zipfile to the directory provided
  4.     It first creates the directory structure to house the files
  5.     then it extracts the files to it.

  6.     Sample usage:
  7.     command line
  8.     unzip.py -p 10 -z c:\testfile.zip -o c:\testoutput

  9.     python class
  10.     import unzip
  11.     un = unzip.unzip()
  12.     un.extract(r'c:\testfile.zip', 'c:\testoutput')
  13.    

  14.     By Doug Tolton
  15. """

  16. import sys
  17. import zipfile
  18. import os
  19. import os.path
  20. import getopt


  21. class unzip:
  22.     def __init__(self, verbose = False, percent = 10):
  23.         self.verbose = verbose
  24.         self.percent = percent
  25.         
  26.     def extract(self, file, dir):
  27.         if not dir.endswith(':') and not os.path.exists(dir):
  28.             os.mkdir(dir)

  29.         zf = zipfile.ZipFile(file)

  30.         # create directory structure to house files
  31.         self._createstructure(file, dir)

  32.         num_files = len(zf.namelist())
  33.         percent = self.percent
  34.         divisions = 100 / percent
  35.         perc = int(num_files / divisions)

  36.         # extract files to directory structure
  37.         for i, name in enumerate(zf.namelist()):

  38.             if self.verbose == True:
  39.                 print "Extracting %s" % name
  40.             elif perc >; 0 and (i % perc) == 0 and i >; 0:
  41.                 complete = int (i / perc) * percent
  42.                 print "%s%% complete" % complete

  43.             if not name.endswith('/'):
  44.                 outfile = open(os.path.join(dir, name), 'wb')
  45.                 outfile.write(zf.read(name))
  46.                 outfile.flush()
  47.                 outfile.close()

  48.         return zf.namelist()               


  49.     def _createstructure(self, file, dir):
  50.         self._makedirs(self._listdirs(file), dir)


  51.     def _makedirs(self, directories, basedir):
  52.         """ Create any directories that don't currently exist """
  53.         for dir in directories:
  54.             curdir = os.path.join(basedir, dir)
  55.             if not os.path.exists(curdir):
  56.                 os.mkdir(curdir)

  57.     def _listdirs(self, file):
  58.         """ Grabs all the directories in the zip structure
  59.         This is necessary to create the structure before trying
  60.         to extract the file to it. """
  61.         zf = zipfile.ZipFile(file)

  62.         dirs = []

  63.         for name in zf.namelist():
  64.             if name.endswith('/'):
  65.                 dirs.append(name)

  66.         dirs.sort()
  67.         return dirs

  68. def usage():
  69.     print """usage: unzip.py -z <zipfile>; -o <targetdir>;
  70.     <zipfile>; is the source zipfile to extract
  71.     <targetdir>; is the target destination

  72.     -z zipfile to extract
  73.     -o target location
  74.     -p sets the percentage notification
  75.     -v sets the extraction to verbose (overrides -p)

  76.     long options also work:
  77.     --verbose
  78.     --percent=10
  79.     --zipfile=<zipfile>;
  80.     --outdir=<targetdir>;"""
  81.    

  82. def main():
  83.     shortargs = 'vhp:z:o:'
  84.     longargs = ['verbose', 'help', 'percent=', 'zipfile=', 'outdir=']

  85.     unzipper = unzip()

  86.     try:
  87.         opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs)
  88.     except getopt.GetoptError:
  89.         usage()
  90.         sys.exit(2)

  91.     zipsource = ""
  92.     zipdest = ""

  93.     for o, a in opts:
  94.         if o in ("-v", "--verbose"):
  95.             unzipper.verbose = True
  96.         if o in ("-p", "--percent"):
  97.             if not unzipper.verbose == True:
  98.                 unzipper.percent = int(a)
  99.         if o in ("-z", "--zipfile"):
  100.             zipsource = a
  101.         if o in ("-o", "--outdir"):
  102.             zipdest = a
  103.         if o in ("-h", "--help"):
  104.             usage()
  105.             sys.exit()

  106.     if zipsource == "" or zipdest == "":
  107.         usage()
  108.         sys.exit()
  109.             
  110.     unzipper.extract(zipsource, zipdest)

  111. if __name__ == '__main__': main()
复制代码



  1. # convert filename & content of utf-8 to gbk

  2. import unzip
  3. import codecs
  4. import sys
  5. import os
  6. import os.path
  7. import zipfile

  8. def usage():
  9.     print """usage: convert.py backupfile
  10.     backupfile is the file saved from wiki"""

  11. def main():
  12.     if (len(sys.argv) <>; 2):
  13.         usage()
  14.         sys.exit()

  15.     backupfile = sys.argv[1]

  16.     if not os.path.isfile(backupfile):
  17.         print ("No such file or not a valid file")
  18.         sys.exit()
  19.             
  20.     if (not zipfile.is_zipfile(backupfile)):
  21.         print "Invalid zip file"
  22.         sys.exit()

  23.     workdir = os.path.dirname(os.path.abspath(backupfile))
  24.     outputdir = os.path.join(workdir, os.path.splitext(backupfile)[0])

  25.     un = unzip.unzip()
  26.     namelist = un.extract(backupfile, os.path.join(workdir, outputdir))
  27.     for i, name in enumerate(namelist):
  28.         i = i + 1
  29.         sys.stdout.write('[%d] ' % i)
  30.         try:
  31.             filename = name.decode('utf-8').encode('gbk')            
  32.         except:
  33.             filename = name
  34.         sys.stdout.write('%s ...' % filename)
  35.         filename = filename + '.txt'
  36.         try:
  37.             infile = codecs.open( os.path.join(outputdir, name), "r", "utf-8")
  38.             content = infile.read()
  39.             infile.close()
  40.             outfile = codecs.open( os.path.join(outputdir, filename), "w", "gbk" )
  41.             outfile.write(content)
  42.             outfile.close()
  43.             print ' done'            
  44.         except:
  45.             print ' failed'
  46.         try:
  47.             os.remove(os.path.join(outputdir, name))
  48.         except:
  49.             pass

  50. if __name__ == '__main__':
  51.     main()
  52.    
复制代码

论坛徽章:
0
发表于 2005-06-11 23:14 |显示全部楼层

用Python快速解决了遇到的一个问题,大家来看看

大家还有什么更好的解决办法?我们一起讨论一下
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP