代码之家  ›  专栏  ›  技术社区  ›  luc

不能删除python glob返回的字符串中的法语字母

  •  3
  • luc  · 技术社区  · 16 年前

    我想用法语字母重命名文件。我正在使用glob浏览文件,并在Internet上找到一个删除法语字母的功能。这个 supprime_accent 似乎工作正常。但是,它不会重命名glob函数返回的文件。

    有人知道原因是什么吗?它与glob编码有关吗?

    def supprime_accent(ligne):
        """ supprime les accents du texte source """
        accents = { 'a': ['à', 'ã', 'á', 'â'],
                    'e': ['é', 'è', 'ê', 'ë'],
                    'i': ['î', 'ï'],
                    'u': ['ù', 'ü', 'û'],
                    'o': ['ô', 'ö'] }
        for (char, accented_chars) in accents.iteritems():
            for accented_char in accented_chars:
                ligne = ligne.replace(accented_char, char)
        return ligne
    
    for file_name in glob.glob("attachments/*.jpg"):
        print supprime_accent(file_name)
    
    3 回复  |  直到 16 年前
        1
  •  2
  •   Jason Orendorff Oliver    16 年前

    我发现这里有两个潜在的问题。

    首先,您需要在源代码中使用Unicode字符串,并且需要 tell Python what encoding the source code is in .不幸的是,如果你做的对,你的表中的元音数就会翻一番…:。-\

    # -*- coding: UTF-8 -*-
    ...
    accents = { u'a': [u'à', u'ã', u'á', u'â'],
                u'e': [u'é', u'è', u'ê', u'ë'],
                u'i': [u'î', u'ï'],
                u'u': [u'ù', u'ü', u'û'],
                u'o': [u'ô', u'ö'] }
    

    其次,我认为您需要转换 glob 到Unicode字符串。

    import sys
    file_name = file_name.decode(sys.getfilesystemencoding())
    

    python 3.0解决了这两个问题:文件名不必解码,Unicode字符串不需要 u 标签。

        2
  •  1
  •   Community Mohan Dere    9 年前

    试着回答这个问题,我已经给出了我使用的最终解决方案。 latin-1 to ascii

    并向glob传递一个unicode字符串,以获取unicode文件名,例如

    for file_name in glob.glob(u"attachments/*.jpg"):
        print file_name.encode('ascii', 'latin2ascii')
    
        3
  •  1
  •   luc    16 年前

    我已经成功地通过将文件名转换为带有CP1252 ENNCODING的Unicode来解决这个问题。

    for file_name in glob.glob("attachments/*.jpg"):
        file_name = file_name.decode(sys.getfilesystemencoding())
        print unicodedata.normalize('NFKD', file_name).encode('ascii','ignore')
    

    编辑:Jason给出了一个更好的解决方案,将unicode(file_name,'cp1252')替换为file_name.decode(sys.getfilesystemcodeding())