Python 删除文件名中的非拉丁字符

Python 删除文件名中的非拉丁字符,python,Python,我一直在解决一个问题,我需要将大量Mac文件和文件夹归档到windows服务器数据磁带上。 当我访问.DS_存储文件和其他mac字符时,会出现问题和挂断。因此,在移动到windows之前,我基本上需要做一个清理步骤。 剩下要做的一件事是查找非拉丁字符,如项目符号字符,然后删除它们或将它们替换为u(下划线字符)。我很难让它工作。 运行时抱怨缩进,我的任何操作都是徒劳的。处理非拉丁字符的代码区是否正常? 任何帮助都将不胜感激 #!/bin/python import os import sys

我一直在解决一个问题,我需要将大量Mac文件和文件夹归档到windows服务器数据磁带上。 当我访问.DS_存储文件和其他mac字符时,会出现问题和挂断。因此,在移动到windows之前,我基本上需要做一个清理步骤。 剩下要做的一件事是查找非拉丁字符,如项目符号字符,然后删除它们或将它们替换为u(下划线字符)。我很难让它工作。
运行时抱怨缩进,我的任何操作都是徒劳的。处理非拉丁字符的代码区是否正常? 任何帮助都将不胜感激

#!/bin/python

import os
import sys

# Help function
def showhelp():
    print "Usage: delete-dsstore.py PATH"
    print "Example: delete-dsstore.py /Users/angelito"


if len(sys.argv) > 1:

    # Check if parameter is a dir
    if os.path.isdir(sys.argv[1]):

        # Clear file counter
        i = 0;

        # Get path
        path  = sys.argv[1];

        # Runs through all files in the directory
        for root, sub, files in os.walk(path):

            for file in files:

                # Checks if exists .DS_Store file
                if file == ".DS_Store":

                    # Get full path of current .DS_Store file
                    fullpath = os.path.abspath(os.path.join(root, file))
                    print "Deleting " + fullpath

                    # Remove file
                    os.remove(fullpath)
                    i += 1

                # Checks if exists .localized file
                if file == ".localized":

                    # Get full path of current .localized file
                    fullpath = os.path.abspath(os.path.join(root, file))
                    print "Deleting " + fullpath

                    # Remove file
                    os.remove(fullpath)
                    i += 1

        # Runs through all files in the directory
        for root, sub, files in os.walk(path):

            # Checks if exists non latin characters like bullets in file names, and delete characters
            for file in files:
                os.rename(file, file.encode('latin-1', 'ignore'))

            # Get full path of current non latin character file
                fullpath = os.path.abspath(os.path.join(root, file))
                print "Modifying " + fullpath

                i += 1

        print str(i) + " files deleted";

    elif sys.argv[1] == '--help':

        # Show help message
        showhelp()

    else:

        print "Argument must be a valid directory"

else:

    showhelp()
试试这个:

p = re.compile(r'[^A-Za-z0-9]')
filename = p.sub('_', filename)
例如:

>>> p.sub('_', 'this-is-it')
'this_is_it'
>>> p.sub('_', 'â ê bla bla bla')
'______bla_bla_bla'

(假设你的意思是ascii…不是拉丁语)

如果你真的是指拉丁字符而不是ascii,那么你的朋友是:

s = u'汉语 / 漢語; Hànyǔ or 中文; Zhōngwén.tmp'

> print regex.sub(u'\p{^Latin}', u'_', s)
_________Hànyǔ_or_____Zhōngwén_tmp

> print regex.sub(u'\p{^Latin}+', u'_', s)
_Hànyǔ_or_Zhōngwén_tmp

> print '.'.join( regex.sub(u'\p{^Latin}+', u'_', t)
                  for t in s.rsplit('.', 1) )
_Hànyǔ_or_Zhōngwén.tmp
如果要保留替换的角色,请执行以下操作:

> print '.'.join( regex.subf(u'\p{^Latin}',
                             lambda m: '_%04x' % ord(m[0]),
                             t)
                  for t in s.rsplit('.', 1) )
_6c49_8bed_0020_002f_0020_6f22_8a9e_003b_0020Hànyǔ_0020or_0020_4e2d_6587_003b_0020Zhōngwén.tmp
可逆的:

regex.subf('_([0-9a-f]{4})', lambda m: unichr(int(m[1], 16)), s)

你真的是指拉丁语还是非ASCII码?例如,
是一个非常好的拉丁字符。是的,我指的是任何不是ASCII 1-255的字符。我不明白我的代码有什么问题:虽然ASCII仅为0-127,但…很抱歉,我包含了扩展字符集,我不想要它。插入下面的代码在脚本中不起作用。斜体粗体
code
#检查文件名中是否存在类似项目符号的非拉丁字符,并删除文件中的文件字符:p=file.compile(r'[^A-Za-z0-9]')#os.rename(文件,文件.encode('latin-1',ignore'))os.rename(file,p.sub(“”,file))#获取当前非拉丁字符文件的完整路径fullpath=os.path.abspath(os.path.join(root,file))打印(“修改”+fullpath)i+=1
Nice clean输出,但它会删除有效的文件名字符,如appos、逗号、方括号……然后将它们添加到正则表达式模式中。我不知道OP真正想要的是什么,所以我提供了一个通用的答案。我想您也需要
。替换('?','''.')
,因为您不能在Windows AFAK中的文件名中使用问号。
regex.subf('_([0-9a-f]{4})', lambda m: unichr(int(m[1], 16)), s)