现在的位置: 首页 > 综合 > 正文

Python处理MLDonkey 下载中文文件乱码问题

2012年11月26日 ⁄ 综合 ⁄ 共 1154字 ⁄ 字号 评论关闭

python文件内容如下:

#
-*- coding: cp936 -*-

import
os ,string ,urllib ,operator

 

#
文件替换目录路径

sdir='/usr/local/mldonkey/incoming/'

 

#
数字标记

sNum='0123456789'

 

#
遍历目录做文件名转换

def
convert():

       filenames=os.listdir(sdir)

       for filename in filenames :

              if filename != convertName(filename)
:

                     print filename + '
>>> ' + convertName(filename)

                     os.rename(sdir + filename
,sdir + convertName(filename))

 

#
转换一个文件名   

def
convertName(s) :

    location = 0

    ret = ""

    while True :

        if location + 8 <= len(s) :

            subStr = s[location:location + 8]

            if check(subStr) :

                ret += "%" +
hex((int)(subStr[1:4]))[2:4] + "%" + hex((int)(subStr[5:8]))[2:4]

                location = location + 8

            else :

                ret += s[location :location +
1]

                location = location + 1

        else :

            ret += s[location:]

            break

    return urllib.unquote(ret)

 

#
检查一个字符串是否需要做转换   

def
check(s):

    if len(s) != 8 :

        return False

 

    if s[0] != '_' or s[4] != '_' :

        return False

 

    if (s[1] in sNum) and (s[2] in sNum) and
(s[3] in sNum) and (s[5] in sNum) and (s[6] in sNum) and (s[7] in sNum) :

        return True

    return False

   

#
执行文件名转换

convert()

要运行此脚步,需要Python2.4,在命令行输入:
python mldonkey.py
运行即可。

抱歉!评论已关闭.