Python-stringのmaketrans,translate関数
まず、この2つの関数の公式定義を見てみましょう.
string.maketrans(from, to):Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.
string.translate(s, table[, deletechars]):Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
次のコードは、この2つの関数をカプセル化します.
string.maketrans(',')メソッドがmaketransを呼び出すと、翻訳テーブルはちょうど256文字の文字列tである.翻訳テーブルで生成される文字列(印刷不可文字を無視)は「!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^`abcdefghijklmnopqrstuvwxyz{|}~」であり、本質的にASCIIテーブルに対応している.
実はmaketrans関数を呼び出すと、変換が完了しました.例えばstring.maketrans('ABCD','abcd')は、呼び出しが完了すると、翻訳テーブルで生成される256文字を含む文字列(印刷不可文字を無視)が「!"#$%&'()*+,-./0123456789:;<=>?@abcdEFGHIJKLMNOPQRSTUVWXYZ[]^`abcdefghijklmnopqrstuvwxyz{}~」、この翻訳テーブルの元の「ABCD」の位置が「abcd」に置き換えられている.
tを最初のパラメータとしてtranslateメソッドに渡すと、元の文字列の各文字cは、処理が完了すると文字t[ord(c)]に翻訳されます.
For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.
次のコードはunicode文字列をフィルタします.
Unicode文字列のtranslateメソッドには、1つのパラメータしか必要ありません.1つのシーケンスまたはマッピングで、文字列内の各文字のコード値に基づいてインデックスを作成します.コード値がマッピングされたキー(またはシーケンスのインデックス値)ではない文字は、変更せずに直接コピーされます.各文字コードに対応する値は、unicode文字列(文字の置換物)またはNone(文字が削除される必要があることを意味する)でなければなりません.通常、unicode文字列のtranslateメソッドのパラメータとしてdictまたはlistを使用して、一部の文字を翻訳または削除します.
string.maketrans(from, to):Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.
string.translate(s, table[, deletechars]):Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.
次のコードは、この2つの関数をカプセル化します.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import string
def translator(frm='', to='', delete='', keep=None):
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
trans_all = string.maketrans('', '')
#keep.translate(trans_all, delete),
#trans_all.translate(trans_all, keep.translate(trans_all, delete)), ,
delete = trans_all.translate(trans_all, keep.translate(trans_all, delete))
def translate(s):
return s.translate(trans, delete)
return translate
if __name__ == '__main__':
#result:12345678
digits_only = translator(keep=string.digits)
print digits_only('Eric chen: 1234-5678')
#result:Eric chen: -
no_digits = translator(delete=string.digits)
print no_digits('Eric chen: 1234-5678')
#result:Eric chen: ****-****
digits_to_hash = translator(frm=string.digits, to='*')
print digits_to_hash('Eric chen: 1234-5678')
string.maketrans(',')メソッドがmaketransを呼び出すと、翻訳テーブルはちょうど256文字の文字列tである.翻訳テーブルで生成される文字列(印刷不可文字を無視)は「!"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^`abcdefghijklmnopqrstuvwxyz{|}~」であり、本質的にASCIIテーブルに対応している.
実はmaketrans関数を呼び出すと、変換が完了しました.例えばstring.maketrans('ABCD','abcd')は、呼び出しが完了すると、翻訳テーブルで生成される256文字を含む文字列(印刷不可文字を無視)が「!"#$%&'()*+,-./0123456789:;<=>?@abcdEFGHIJKLMNOPQRSTUVWXYZ[]^`abcdefghijklmnopqrstuvwxyz{}~」、この翻訳テーブルの元の「ABCD」の位置が「abcd」に置き換えられている.
tを最初のパラメータとしてtranslateメソッドに渡すと、元の文字列の各文字cは、処理が完了すると文字t[ord(c)]に翻訳されます.
For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.
次のコードはunicode文字列をフィルタします.
import sets
class Keeper(object):
def __init__(self, keep):
self.keep = sets.Set(map(ord, keep))
def __getitem__(self, n):
if n not in self.keep:
return None
return unichr(n)
def __call__(self, s):
return unicode(s).translate(self)
makeFilter = Keeper
if __name__ == '__main__':
#result:
just_people = makeFilter(u' ')
print just_people(u' ')
# unicode
#result: !
translate_table = dict((ord(char), None) for char in u' ')
print unicode(u' !').translate(translate_table)
# unicode
#result: ** !
translate_table = dict((ord(char), u'*') for char in u' ')
print unicode(u' !').translate(translate_table)
Unicode文字列のtranslateメソッドには、1つのパラメータしか必要ありません.1つのシーケンスまたはマッピングで、文字列内の各文字のコード値に基づいてインデックスを作成します.コード値がマッピングされたキー(またはシーケンスのインデックス値)ではない文字は、変更せずに直接コピーされます.各文字コードに対応する値は、unicode文字列(文字の置換物)またはNone(文字が削除される必要があることを意味する)でなければなりません.通常、unicode文字列のtranslateメソッドのパラメータとしてdictまたはlistを使用して、一部の文字を翻訳または削除します.