2015-10-22 56 views
1

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

到目前为止的代码:

# -*- 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 
+0

更换不修改它会返回修改过的字符串... –

+2

[为什么不调用Python字符串方法会执行任何操作,除非分配它的输出?](http:// stackover flow.com/faqs/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) –

+2

我不确定适当的词是什么,但“变音符“是指用于标记变音符号的两个点,而不是两个字母的拼写替代。 – chepner

回答

4

replace方法返回一个新的字符串,它不会修改原始字符串。

所以你需要

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) 
+0

是的!翻译作品完美。感谢您的快速反馈! –

0

替换行

file.replace(key, value) 

有:

file = file.replace(key, value) 

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

这意味着file.replace(key, value)返回副本file与取代

+1

从dublicate问题的好复制粘贴^^ – inetphantom