python - 根据字典替换字符串的快速方法

标签 python string performance replace

我想根据字典替换一个很长的字符串。我的代码是这样的:

def rep(self, mystr, dict):
    new_pstr = ''
    for char in mystr:
        try:
            new_pstr += dict[char]
        except:
            continue
    return new_pstr

这段代码没有我预期的那么快。也许没有循环,它会更快。但我不知道该怎么做。最后但并非最不重要的一点是,我不能一起替换所有相同的字符,每次我应该只替换一个字符。因此,替换功能可能不是我的选择。为了更清楚,我举个例子:

如果 d = {'A':'C', 'C':'B'}mystr = 'AC',则 new_pstr ='CB'

(如果你的方式返回我'BB',这不是我所期望的)

在实际情况中,我的字典看起来像这样:

d = {u'q': [u'k'], u'v': [u'v'], u'e': [u'e'], u'\xe7': [u'\xe7'], u'\xe9': [u'e'], u'h': [u'y'], u'j': [u'z'], u'o': [u'u'], u'\xf1': [u'g'], u'i': [u'i'], u'\u015f': [u's'], u'\xf6': [u'u'], u'x': [u'x'], u'\xfc': [u'v'], u'\u011f': [u'g']}

我的字符串是这样的:

str = "tériniñ yiriklişip kétişi havadiki nemlikniñ tövenlep ketkenlikidin bolup ، bu vaqitta tére téximu qurğaqlişip kétidu ، tériniñ ilastikiliqi acizlap ، xünük bolup qalidu. şuña xanim – qizlar bundaq vaqitta tére qurğaqlişişniñ aldini alidiğan çare– tedbirlerni qolliniş kérek. nemlikni saqlaşta yuquri dericilik su toluqlaş yüzlüki، hesel ve örük méğizi méyiğa muvapiq miqdarda un arilaşturup melhem qilip yüzge çaplap bers e، yaki nemxuşluqi yuquri bolğan tére nemleştürüş vazilin méyi sürüp berse، qurğaq térige su toluqlaşqa paydiliq."

我使用 try.. except ... 的原因是因为我的代码有时会返回类似 UnicodeEncodeError: 'ascii' codec can't Encode character 的错误u'\xe7' 位于位置 2:序号不在范围(128)

最佳答案

查阅此Tutorial 。它可能对你有帮助。

The method translate() returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string deletechars.

示例代码:

以下是从字符串中删除“x”和“m”字符的示例:

#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab, 'xm')

这将产生以下结果 -

th3s 3s str3ng 21pl2....w4w!!!

source这段代码。

关于python - 根据字典替换字符串的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100017/

相关文章:

python - 使用 web2py 模仿输入的 HTML5 模式属性的行为?

python - 我已经使用这个文档字符串语法两年了,它叫什么,谁指定它,使用它是 "ok"吗?

sql - 在 SQL Server 中修剪前导零的更好技术?

arrays - 为什么这个 string.match 不能持续工作?

python - 如何在python中获取文件移动的进度?

c - 字符串如何在 C 中工作?

python - 在 Pandas 中创建许多新列的最 Pythonic 方式

java - Google Dataflow批处理文件处理性能不佳

ruby-on-rails - Rails 路由顺序会影响性能吗?

Python 撤消 Unicode