使用 Python 进行字符翻译(如 tr 命令)
有没有办法进行字符翻译/音译(有点像 tr
命令)使用Python?
Perl 中的一些例子是:
my $string = "some fields";
$string =~ tr/dies/eaid/;
print $string; # domi failed
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n"; # b b b. (because option "d" is used to delete characters not replaced)
Is there a way to do character translation / transliteration (kind of like the tr
command) using Python?
Some examples in Perl would be:
my $string = "some fields";
$string =~ tr/dies/eaid/;
print $string; # domi failed
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n"; # b b b. (because option "d" is used to delete characters not replaced)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请参阅
string.translate
请注意文档的注释关于 unicode 字符串翻译中的微妙之处。
对于Python 3,您可以直接使用:
编辑:由于
tr
有点高级,也可以考虑使用re.sub
。See
string.translate
Note the doc's comments about subtleties in the translation of unicode strings.
And for Python 3, you can use directly:
Edit: Since
tr
is a bit more advanced, also consider usingre.sub
.如果您使用的是 python3,翻译就不那么冗长:
啊..并且还有相当于
tr -d
:对于带有 python2.x 的
tr -d
使用附加参数翻译功能:If you're using python3 translate is less verbose:
Ahh.. and there is also equivalent to
tr -d
:For
tr -d
with python2.x use an additional argument to translate function:我开发了python-tr,实现了tr算法。
我们来试试吧。
安装:
示例:
I has developed python-tr, implemented tr algorithm.
Let's try it.
Install:
Example:
在 Python 2 中,
unicode.translate()
接受普通映射,即。 也无需导入任何内容:translate()
方法对于交换字符(如上面的“+”和“-”)特别有用,而replace( 无法做到这一点) )
,并且使用re.sub()
也不是很简单。然而,我不得不承认,重复使用
ord()
并不会让代码看起来漂亮整洁。In Python 2,
unicode.translate()
accepts ordinary mappings, ie. there's no need to import anything either:The
translate()
method is especially useful for swapping characters (as '+' and '-' above), which can't be done withreplace()
, and usingre.sub()
isn't very straightforward for that purpose either.I have to admit, however, that the repeated use of
ord()
doesn't make the code look like nice and tidy.我们绘制地图,然后逐字翻译。 当对字典使用 get 时,第二个参数指定如果没有找到任何内容则返回什么。
它可以很容易地转移到单独的功能。 大多数情况下应该非常高效。
We build a map and then translate letter by letter. When using get for dictionary then the second argument specifying what to return if not find anything.
It could be easily transferred to separate function. Mostly should be very efficient.
更简单的方法可能是使用替换。 例如
不需要导入任何东西。 适用于 Python 2.x
A simpler approach may be to use replace. e.g.
No need to import anything. Works in Python 2.x