Python的chartR等价物

2024-04-25 23:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

有了chartr()(R)函数,生活就那么简单了:

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

返回"my text is plan of accent"

在Python中re.sub()函数只在第二个参数上取一个替换值:

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

是否有与chartr()等价的Python函数?你知道吗


Tags: of函数textre参数ismyxt
2条回答
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)

我相信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 

相关问题 更多 >