Cra*_*tto 2 python unicode transliteration
我有一个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
Run Code Online (Sandbox Code Playgroud)
该replace方法返回一个新字符串,它不会修改原始字符串。
所以你需要
file = file.replace(key, value)
Run Code Online (Sandbox Code Playgroud)
而不只是 file.replace(key, value)。
还需要注意的是,你可以使用的translate方法来完成所有的更换一次,而不是使用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
Run Code Online (Sandbox Code Playgroud)
所以你可以使用
umap = {ord(key):unicode(val) for key, val in umlautDictionary.items()}
for filename in filePathsList:
filename = filename.translate(umap)
print(filename)
Run Code Online (Sandbox Code Playgroud)