Python - 将德语变音符号音译为变音符号

Python - Transliterate German Umlauts to Diacritic

我有一个 unicode 文件路径列表,我需要用英语变音符号替换其中的所有变音符号。例如,我会将 ü 与 ue,ä 与 ae 等。我已经定义了变音符号(键)及其变音符号(值)的字典。所以我需要将每个键与每个文件路径以及找到键的位置进行比较,将其替换为值。这看起来很简单,但我无法让它工作。有没有人有任何想法?非常感谢任何反馈!

到目前为止的代码:

# -*- coding: utf-8 -*-

import os

def GetFilepaths(directory):
    """
    This function will generate all file names a directory tree using os.walk.
    It returns a list of file paths.
    """
    file_paths = []
    for root, directories, files in os.walk(directory):
        for filename in files:
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)
    return file_paths

# dictionary of umlaut unicode representations (keys) and their replacements (values)
umlautDictionary = {u'Ä': 'Ae',
                    u'Ö': 'Oe',
                    u'Ü': 'Ue',
                    u'ä': 'ae',
                    u'ö': 'oe',
                    u'ü': 'ue'
                    }

# get file paths in root directory and subfolders
filePathsList = GetFilepaths(u'C:\Scripts\Replace Characters\Umlauts')
for file in filePathsList:
    for key, value in umlautDictionary.iteritems():
        if key in file:
            file.replace(key, value) # does not work -- umlauts still in file path!
            print file

替换行

file.replace(key, value)

与:

file = file.replace(key, value)

这是因为字符串在Python中是不可变的。

这意味着 file.replace(key, value) returns file 的副本

replace方法returns一个新的字符串,它不修改原来的字符串。

所以你需要

file = file.replace(key, value)

而不仅仅是 file.replace(key, value).


另请注意,您可以使用 the translate method 一次完成所有替换,而不是使用 for-loop:

In [20]: umap = {ord(key):unicode(val) for key, val in umlautDictionary.items()}

In [21]: umap
Out[21]: {196: u'Ae', 214: u'Oe', 220: u'Ue', 228: u'ae', 246: u'oe', 252: u'ue'}

In [22]: print(u'ÄÖ'.translate(umap))
AeOe

所以你可以使用

umap = {ord(key):unicode(val) for key, val in umlautDictionary.items()}
for filename in filePathsList:
    filename = filename.translate(umap)
    print(filename)