• 第一个python小程序


      刚刚开始学习python,花了点时间看了python语法,网上那个python简明教程感觉真不错又结合了一个园友写的系列文章,基本算是把python语法入门了。恰好一个朋友向我抱怨他的一个项目文档乱码问题,就想着用python写一个转换编码的程序来练练手。代码如下:

     1 #!/usr/bin/python
     2 #-*- coding: utf-8 -*-
     3 
     4 # Filename: gb_to_utf8.py dirname
     5 # GB2312 to UTF-8
     6 
     7 import os
     8 import os.path
     9 import sys
    10 import chardet
    11 
    12 def convert_code(filename, in_enc = 'gbk', out_enc = 'utf-8'):
    13     """
    14     
    15     Arguments:
    16     - `filename`:
    17     - `in_enc`:
    18     - `out_enc`:
    19     """
    20     try:
    21         print 'convert:', filename
    22         f = open(filename, 'rb')
    23         data = f.read()
    24         f.close()
    25         in_enc = chardet.detect(data)['encoding']
    26         # print in_enc
    27         new_contert = data.decode(in_enc, 'ignore')
    28         new_data = new_contert.encode(out_enc, 'ignore')
    29         f = open(filename, 'w')
    30         f.write(new_data)
    31         f.close()
    32         print 'Success:', filename, 'converted from', in_enc, 'to', out_enc, '!'
    33         print
    34     except:
    35         print 'Error, fail convert:', filename
    36         print
    37 
    38 def get_filename_list(dirname, suffix = ''):
    39     """
    40     
    41     Arguments:
    42     - `dirname`:
    43     - `suffix`:
    44     """
    45     flist = []
    46     for root, dirs, files in os.walk(dirname):
    47         for name in files:
    48             if name.endswith(suffix):
    49                 flist.append(os.path.join(root, name))
    50     return flist
    51 
    52 def explore(name):
    53     """
    54     """
    55     dirname = os.path.join(os.getcwd(), name)
    56     flist = get_filename_list(dirname)
    57     for fname in flist:
    58         convert_code(fname)
    59     print 'Finished!'
    60 
    61 def main(argv):
    62     """
    63     """
    64     explore(argv)
    65 
    66 if __name__ == '__main__':
    67     main(sys.argv[1])

    程序用了chardet包,可能默认python是没有安装的,apt-get或者yum搞定。

    需要转换编码文件的文件夹名字作为参数传递给程序: python convert.py filedir

    程序调用os.walk()函数,就能得到文件夹下面所有文件名(包裹子文件夹下面的),放在一个list里面。接着遍历list,每次取出一个文件处理:读出文件内容,chardet.detect得到内容编码格式(存储在一个字典里面),然后用它的编码格式decode,然后用utf-8格式(可以换成任何你想要转换成为的格式)encode,重新写入文件,就转换成功了。

  • 相关阅读:
    什么是 bean 的自动装配?
    什么是 Spring 的内部 bean?
    什么是 Spring 的 MVC 框架?
    Spring AOP and AspectJ AOP 有什么区别?
    解释 JDBC 抽象和 DAO 模块?
    volatile 类型变量提供什么保证?
    一个 Spring Bean 定义 包含什么?
    什么是 Spring MVC 框架的控制器?
    使用 Spring 访问 Hibernate 的方法有哪些?
    什么是 Callable 和 Future?
  • 原文地址:https://www.cnblogs.com/Franck/p/2863205.html
Copyright © 2020-2023  润新知