- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
php 有 strtr
功能:
strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y
它用相应的值替换字符串中的字典键,并且(重要的)不替换已经替换的字符串。在 python 中编写相同的天真尝试:
def strtr(strng, replace):
for s, r in replace.items():
strng = strng.replace(s, r)
return strng
strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'})
返回 xz-x-y
这不是我们想要的(bb
再次被替换)。如何更改上述函数,使其表现得像对应的 php 函数?
(如果可能的话,我更喜欢没有正则表达式的答案)。
更新:这里有一些很好的答案。我对它们进行了计时,发现对于短字符串,Gumbo 的版本似乎是最快的,对于较长的字符串,获胜者是 re
解决方案:
# 'aa-bb-cc'
0.0258 strtr_thg
0.0274 strtr_gumbo
0.0447 strtr_kojiro
0.0701 strtr_aix
# 'aa-bb-cc'*10
0.1474 strtr_aix
0.2261 strtr_thg
0.2366 strtr_gumbo
0.3226 strtr_kojiro
我自己的版本(略微优化了 Gumbo 的版本):
def strtr(strng, replace):
buf, i = [], 0
while i < len(strng):
for s, r in replace.items():
if strng[i:len(s)+i] == s:
buf.append(r)
i += len(s)
break
else:
buf.append(strng[i])
i += 1
return ''.join(buf)
完整的代码和时间:https://gist.github.com/2889181
最佳答案
下面使用正则表达式来做:
import re
def strtr(s, repl):
pattern = '|'.join(map(re.escape, sorted(repl, key=len, reverse=True)))
return re.sub(pattern, lambda m: repl[m.group()], s)
print(strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'}))
与 PHP 版本一样,这会优先考虑较长的匹配项。
关于python - php 的 strtr for python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931150/
在哪里可以找到不区分大小写的 strtr 版本? strtr 重载了,我说的是下面这个 string strtr ( string $str , array $replace_pairs ) 最佳答案
你好吗。希望很好... 我遇到了以下代码的问题。 strtr 函数不工作。它不输出任何东西... if ($translate == "DrChatrikWeb") { $convertarray =
我从 php.net 获得了以下代码: $GLOBALS['normalizeChars'] = array( 'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=
我很难从某些 $string 中删除变音符号。我的代码是 'r', 'í' => 'i', 'š' => 's', 'ž' => 'z', 'ť' => 't', 'č' =>
有没有人写过函数 strtr() 的多字节变体?我需要这个。 编辑 1(所需用法示例): Example:$from = 'ľľščťžýáíŕďňäô'; // these chars are in
我很好奇执行字符串转换的最高效方法是什么。给定 n 个输入字符串和一组翻译,通常哪种方法最有效?我目前使用 strtr(),但已经测试了各种循环方法、使用数组的 str_replace() 等。str
我很好奇执行字符串转换的最高效方法是什么。给定 n 个输入字符串和一组翻译,通常哪种方法最有效?我目前使用 strtr(),但已经测试了各种循环方法、使用数组的 str_replace() 等。str
php 有 strtr功能: strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y')); # bbz-x-y 它用相应的值替换
我很难理解何时 strtr 比 str_replace 更可取,反之亦然。尽管替换子字符串的顺序相反,但似乎可以使用任一函数获得完全相同的结果。例如: echo strtr('test string'
在网上看了一些php优化的指南,里面提到:使用strtr 函数 比 str_replace快4倍。 本着探索的精神动手验证。 代码 ?
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
这是我的 PHP 代码,它完成了我需要它完成的工作,但它需要重新加载页面才能真正工作。 "a","б" => "b","в" => "v","г" => "g","д" => "d","е" =>
我正在为 PHP 寻找 UTF-8 兼容的 strtr。 最佳答案 function strtr_utf8($str, $from, $to) { $keys = array(); $
$search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); $subject = '
我是一名优秀的程序员,十分优秀!