Python string 模块,translate() 实例源码
我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用string.translate()。
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def strip_punctuation(text):
"""
strips the punctuation from a bunch of text
"""
# build a translation table for string.translate:
# there are other ways to do this:
# create a translation table to replace all punctuation with spaces
# -- then split() will remove the extra spaces
punctuation = string.punctuation
punctuation = punctuation.replace("'", "") # keep apostropies
punctuation = punctuation.replace("-", "") # keep hyphenated words
# building a translation table
table = {}
for c in punctuation:
table[ord(c)] = ' '
# remove punctuation with the translation table
text = text.translate(table)
# remove "--" -- can't do multiple characters with translate
text = text.replace("--", " ")
return text
def do_simple_substitution(ciphertext, pt_charset, ct_charset):
'''
Perform simple substitution based on character sets
Simplifies the use of string.translate(). If, for instance, you wish to
transform a ciphertext where 'e' is swapped with 't', you would call this
function like so:
do_simple_substitution('Simplt subeieueion ciphtrs art silly','et','te')
ciphertext - A string to translate
pt_charset - The character set of the plaintext, usually 'abcdefghijk...xyz'
ct_charset - The character set of the ciphertext
'''
#translate ciphertext to plaintext using mapping
return string.translate(ciphertext, string.maketrans(ct_charset, pt_charset))
# TODO: Implement chi square
def morse_decode(text, dot='.', dash='-', space=' '):
'''
Decodes a Morse encoded message. Optionally, you can provide an alternate
single character for dot, dash, and space.
Parameters:
text - (string) A message to decode
dot - (char) An alternate dot char
dash - (char) An alternate dash char
space - (char) A char to split the text on
'''
inverse_morse_table = map(lambda (x,y): (y,x), morse_table.items())
dot_dash_trans = string.maketrans('.-', dot+dash)
inverse_morse_table = [(string.translate(x,dot_dash_trans), y) for (x,y) in inverse_morse_table]
inverse_morse_table = dict(inverse_morse_table)
return ''.join([inverse_morse_table[char] for char in text.split(space) if char in inverse_morse_table.keys()])
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def BibTeXString(d):
res = ['@'+d['bibtype']+ '{ ' + d['id'] + ',']
inner = []
fill = ' '
for n in StandardBibTeXOrder:
if d.has_key(n):
if len(NormalizedWhitespace(d[n])) > 0:
if n in ['author','editor']:
inner.append(' '+n+' = '+fill[0:16-len(n)]+'{'+normedNamesString(d[n])+'}')
else:
inner.append(' '+n+' = '+fill[0:16-len(n)]+'{'+d[n]+'}')
for n in d.keys():
if not n in StandardBibTeXOrder and not n in ['bibtype', 'id']:
inner.append(' '+n+' = '+fill[0:16-len(n)]+'{'+d[n]+'}')
res.append(string.join(inner, ',\n'))
res.append("}\n")
return string.join(res, "\n")
# (re)translate a Bib entry into a string for a BibXML file
def _normalize(title,charset = 'utf-8'):
'''Removes all accents and illegal chars for titles from the String'''
if isinstance(title,unicode):
title = string.translate(title,allchars,deletechars)
try:
title = title.encode("utf-8")
title = normalize('NFKD',title ).encode('ASCII','ignore')
except UnicodeEncodeError:
logger.error("Error de encoding")
else:
title = string.translate(title,allchars,deletechars)
try:
#iso-8859-1
title = title.decode(charset).encode('utf-8')
title = normalize('NFKD', unicode(title,'utf-8'))
title = title.encode('ASCII','ignore')
except UnicodeEncodeError:
logger.error("Error de encoding")
return title
#
def _normalize(title,charset = 'utf-8'):
'''Removes all accents and illegal chars for titles from the String'''
if isinstance(title,unicode):
title = string.translate(title,allchars,deletechars)
try:
title = title.encode("utf-8")
title = normalize('NFKD',title ).encode('ASCII','ignore')
except UnicodeEncodeError:
logger.info("Error de encoding")
else:
title = string.translate(title,allchars,deletechars)
try:
#iso-8859-1
title = title.decode(charset).encode('utf-8')
title = normalize('NFKD', unicode(title,'utf-8'))
title = title.encode('ASCII','ignore')
except UnicodeEncodeError:
logger.info("Error de encoding")
return title
#
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
print msg + ":"
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
opt_name = opt_name[0:-1]
if opt_name in self.negative_opt:
opt_name = string.translate(self.negative_opt[opt_name],
longopt_xlate)
val = not getattr(self, opt_name)
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
print " %s: %s" % (opt_name, val)
def get_pattern(stuff):
first = "abcdefghijklmnopqrstuvwxyz0123456789"
next = "bcdefghijklmnopqrstuvwxyz0123456789a"
table = string.maketrans(first, next)
textString.append("".join(number))
for run in range(stuff - 1):
if number[2] == '9':
nextNumber = string.translate(number[1], table)
number[1] = nextNumber
if number[1] == '9' and number[2] == '9':
nextNumber = string.translate(number[0], table)
number[0] = nextNumber
nextNumber = string.translate(number[2], table)
number[2] = nextNumber
textString.append("".join(number))
return textString
def set(self, key, val, coded_val,
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters
if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it.
self.key = key
self.value = val
self.coded_value = coded_val
# end set
def _normalize(title, charset='utf-8'):
'''Removes all accents and illegal chars for titles from the String'''
if isinstance(title, unicode):
title = string.translate(title, allchars, deletechars)
try:
title = title.encode("utf-8")
title = normalize('NFKD', title).encode('ASCII', 'ignore')
except UnicodeEncodeError:
logger.error("Error de encoding")
else:
title = string.translate(title, allchars, deletechars)
try:
# iso-8859-1
title = title.decode(charset).encode('utf-8')
title = normalize('NFKD', unicode(title, 'utf-8'))
title = title.encode('ASCII', 'ignore')
except UnicodeEncodeError:
logger.error("Error de encoding")
return title
#
def __init__(self, preserve, translate, other):
"""
Arguments::
preserve: a string of characters to preserve
translate: a dict or key/value list of characters to translate
other: the character to return for all characters not in
preserve or translate
"""
self.table = dict(
(k if isinstance(k, int) else ord(k), v)
for k,v in six.iteritems(dict(translate)) )
for c in preserve:
_c = ord(c)
if _c in self.table and self.table[_c] != c:
raise RuntimeError("Duplicate character '%s' appears in both "
"translate table and preserve list" % (c,))
self.table[_c] = c
self.other = other
def foo():
s='vbkq{ukCkS_vrduztucCVQXVuvzuckrvtZDUBTGYSkvcktv}'
'''
'''
a=string.lowercase
b=""
for i in xrange(len(a)):
if i%2==0:
if i<19:
b+=a[i+7]
else:
b+=a[i-19]
else:
if i>=7:
b+=a[i-7]
else:
b+=a[i+19]
table=string.maketrans(a,b)
print string.translate(s,table)
def get_attr_name (self, long_option):
"""Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores."""
return string.translate(long_option, longopt_xlate)
def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return string.translate(opt, longopt_xlate)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def get_attr_name (self, long_option):
"""Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores."""
return string.translate(long_option, longopt_xlate)
def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return string.translate(opt, longopt_xlate)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def set(self, key, val, coded_val,
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters
if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it.
self.key = key
self.value = val
self.coded_value = coded_val
# end set
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def set(self, key, val, coded_val,
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters
if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it.
self.key = key
self.value = val
self.coded_value = coded_val
# end set
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def set(self, key, val, coded_val,
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters
if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it.
self.key = key
self.value = val
self.coded_value = coded_val
# end set
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def set(self, key, val, coded_val,
LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
# First we verify that the key isn't a reserved word
# Second we make sure it only contains legal characters
if key.lower() in self._reserved:
raise CookieError("Attempt to set a reserved key: %s" % key)
if "" != translate(key, idmap, LegalChars):
raise CookieError("Illegal key value: %s" % key)
# It's a good key, so save it.
self.key = key
self.value = val
self.coded_value = coded_val
# end set
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def update(self, data):
if self._op:
return translate(data, self._encrypt_table)
else:
return translate(data, self._decrypt_table)
def output_mask(text, charset):
'''
Output masking - mask all characters besides those in the provided character
set with dots.
Parameters:
(string) text - output to mask
(string) charset - string containing acceptable characters
'''
all_chars = output_chars = map(chr,range(256))
charset = set(charset)
for charnum in range(256):
if all_chars[charnum] not in charset:
output_chars[charnum] = '.'
return string.translate(text,''.join(output_chars))
def morse_encode(text, dot='.', dash='-', space=' '):
'''
Encodes text into Morse code.
'''
dot_dash_trans = string.maketrans('.-', dot+dash)
translated_morse_table = map(lambda (x,y): (x, string.translate(y, dot_dash_trans)), morse_table.items())
translated_morse_table = dict(translated_morse_table)
output = []
for char in text.lower():
if char in string.lowercase + string.digits:
output.append(translated_morse_table[char])
return space.join(output)
def get_attr_name (self, long_option):
"""Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores."""
return string.translate(long_option, longopt_xlate)
def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return string.translate(opt, longopt_xlate)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def get_attr_name (self, long_option):
"""Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores."""
return string.translate(long_option, longopt_xlate)
def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return string.translate(opt, longopt_xlate)
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote
def _quote(str, LegalChars=_LegalChars,
idmap=_idmap, translate=string.translate):
#
# If the string does not need to be double-quoted,
# then just return the string. Otherwise, surround
# the string in doublequotes and precede quote (with a \)
# special characters.
#
if "" == translate(str, idmap, LegalChars):
return str
else:
return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote