2017-08-31 77 views
1

壽命是很容易與chartr()(R)功能:Python的等效CHARTR

txtdata = "my têxt is plaîn of accent" 
chartr("îêéè", "ieee", txtdata) 

返回"my text is plan of accent"

在Python的re.sub()函數採用在第二ARG只有一個替換值:

re.sub("[éè]", "e", txtdata) 

是否有一個與chartr()相當的Python函數?

回答

3

我相信str.translate更適合這樣的任務,因爲口音翻譯。

out = "my têxt is plaîn of accent".translate(str.maketrans("îêéè", "ieee")) 
print(out) 
'my text is plain of accent' 

100000 loops, best of 3: 3.05 µs per loop 
0
def chartr(to_replace=None,to_replace_by=None,text=None): 
     if len(to_replace) == len(to_replace_by): 
      to_replace = list(to_replace) 
      to_replace_by = list(to_replace_by) 
      for i in range(0,len(to_replace)): 
        text = re.sub(to_replace[i], to_replace_by[i], text) 
      return(text) 
     else: 
      return("length must be the same") 
chartr("éeàâäî","eeaaai",body)