Python string.translate() Examples

The following are 30 code examples of string.translate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: sport365.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def derot(xset, hset, src):
    xset = eval(xset)
    hset = eval(hset)

    import string
    o = ''
    u = ''
    il = 0
    for first in hset:
        u += first
        o += xset[il]
        il += 1
    rot13 = string.maketrans(o, u)
    link = string.translate(src, rot13)
    xbmc.log('@#@DEROT-LINK: %s' % link, xbmc.LOGNOTICE)
    return link 
Example #2
Source File: helpers.py    From featherduster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #3
Source File: subtitletools.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
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

    # 
Example #4
Source File: classical.py    From featherduster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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()]) 
Example #5
Source File: install.py    From BinderFilter with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: fancy_getopt.py    From datafari with Apache License 2.0 5 votes vote down vote up
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) 
Example #7
Source File: one_time_pad.py    From CryptoAttacks with MIT License 5 votes vote down vote up
def break_rot(ciphertext, alphabet=string.lowercase):
    for rot in range(len(alphabet)):
        tr = string.maketrans(alphabet, ''.join([alphabet[rot:], alphabet[:rot]]))
        print(rot, string.translate(ciphertext, tr)) 
Example #8
Source File: table.py    From shadowsocksR-b with Apache License 2.0 5 votes vote down vote up
def update(self, data):
        if self._op:
            return translate(data, self._encrypt_table)
        else:
            return translate(data, self._decrypt_table) 
Example #9
Source File: fancy_getopt.py    From datafari with Apache License 2.0 5 votes vote down vote up
def translate_longopt(opt):
    """Convert a long option name to a valid Python identifier by
    changing "-" to "_".
    """
    return string.translate(opt, longopt_xlate) 
Example #10
Source File: Design_Map_Reduce.py    From Leetcode with MIT License 5 votes vote down vote up
def remove_punctuation(s):
    return s.translate(string.maketrans("",""), string.punctuation) 
Example #11
Source File: Cookie.py    From datafari with Apache License 2.0 5 votes vote down vote up
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 
Example #12
Source File: Cookie.py    From datafari with Apache License 2.0 5 votes vote down vote up
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 
Example #13
Source File: table.py    From ShadowSocks-Client with GNU General Public License v3.0 5 votes vote down vote up
def update(self, data):
        if self._op:
            return translate(data, self._encrypt_table)
        else:
            return translate(data, self._decrypt_table) 
Example #14
Source File: Cookie.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #15
Source File: fancy_getopt.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def translate_longopt(opt):
    """Convert a long option name to a valid Python identifier by
    changing "-" to "_".
    """
    return string.translate(opt, longopt_xlate) 
Example #16
Source File: fancy_getopt.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #17
Source File: table.py    From shadowsocks-analysis with Apache License 2.0 5 votes vote down vote up
def update(self, data):
        if self._op:
            return translate(data, self._encrypt_table)
        else:
            return translate(data, self._decrypt_table) 
Example #18
Source File: table.py    From ShadowsocksFork with Apache License 2.0 5 votes vote down vote up
def update(self, data):
        if self._op:
            return translate(data, self._encrypt_table)
        else:
            return translate(data, self._decrypt_table) 
Example #19
Source File: hackhttp.py    From w9scan with GNU General Public License v2.0 5 votes vote down vote up
def set(
        self, key, val, coded_val,
            LegalChars=Cookie._LegalChars + ':',
            idmap=string._idmap, translate=string.translate):
        return super(MorselHook, self).set(
            key, val, coded_val, LegalChars, idmap, translate) 
Example #20
Source File: breakkey.py    From CodeIgniterXor with GNU General Public License v3.0 5 votes vote down vote up
def cleanstring(inputstring):
    ''' Replace all non-printable characters with dots to avoid breaking our terminal '''
    filter = ''.join([['.', chr(x)][chr(x) in string.printable[:-5]] for x in xrange(256)])
    return string.translate(inputstring, filter) 
Example #21
Source File: ttfonts.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def SUBSETN(n,table=string.maketrans(b'0123456789',b'ABCDEFGIJK'),translate=string.translate):
        return translate('%6.6d'%n,table)
#
# Helpers
# 
Example #22
Source File: ttfonts.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def SUBSETN(n,table=bytes.maketrans(b'0123456789',b'ABCDEFGIJK')):
        return bytes('%6.6d'%n,'ASCII').translate(table) 
Example #23
Source File: table.py    From shadowsocksr with Apache License 2.0 5 votes vote down vote up
def update(self, data):
        if self._op:
            return translate(data, self._encrypt_table)
        else:
            return translate(data, self._decrypt_table) 
Example #24
Source File: Cookie.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #25
Source File: Cookie.py    From pmatic with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #26
Source File: _scons_textwrap.py    From pivy with ISC License 5 votes vote down vote up
def _munge_whitespace(self, text):
        """_munge_whitespace(text : string) -> string

        Munge whitespace in text: expand tabs and convert all other
        whitespace characters to spaces.  Eg. " foo\tbar\n\nbaz"
        becomes " foo    bar  baz".
        """
        if self.expand_tabs:
            text = string.expandtabs(text)
        if self.replace_whitespace:
            if isinstance(text, type('')):
                text = string.translate(text, self.whitespace_trans)
            elif isinstance(text, unicode):
                text = string.translate(text, self.unicode_whitespace_trans)
        return text 
Example #27
Source File: classical.py    From featherduster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #28
Source File: helpers.py    From featherduster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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)) 
Example #29
Source File: fancy_getopt.py    From oss-ftp with MIT License 5 votes vote down vote up
def translate_longopt(opt):
    """Convert a long option name to a valid Python identifier by
    changing "-" to "_".
    """
    return string.translate(opt, longopt_xlate) 
Example #30
Source File: arya.py    From Arya with GNU General Public License v3.0 5 votes vote down vote up
def b64sub(s, key):
    """
    "Encryption" method that base64 encodes a given string, 
    then does a randomized alphabetic letter substitution.
    """
    enc_tbl = string.maketrans(string.ascii_letters, key)
    return string.translate(base64.b64encode(s), enc_tbl)