2015-10-22 54 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