当前位置: 首页>>代码示例>>Python>>正文


Python string.maketrans方法代码示例

本文整理汇总了Python中string.maketrans方法的典型用法代码示例。如果您正苦于以下问题:Python string.maketrans方法的具体用法?Python string.maketrans怎么用?Python string.maketrans使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在string的用法示例。


在下文中一共展示了string.maketrans方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: derot

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
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 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:18,代码来源:sport365.py

示例2: istext

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def istext(self,cont):
        # Based on http://code.activestate.com/recipes/173220/
        import string
        text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
        _null_trans = string.maketrans("", "")
        if not cont:
            # Empty files are considered text
            return True
        if "\0" in cont:
            # Files with null bytes are likely binary
            return False
        # Get the non-text characters (maps a character to itself then
        # use the 'remove' option to get rid of the text characters.)
        t = cont.translate(_null_trans, text_characters)
        # If more than 30% non-text characters, then
        # this is considered a binary file
        if float(len(t))/float(len(cont)) > 0.30:
            return False
        return True 
开发者ID:omriher,项目名称:CapTipper,代码行数:21,代码来源:CTMagic.py

示例3: _ebcdic_to_ascii

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def _ebcdic_to_ascii(self, s):
        c = self.__class__
        if not c.EBCDIC_TO_ASCII_MAP:
            emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
                    16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
                    128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
                    144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
                    32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
                    38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
                    45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
                    186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
                    195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,
                    201,202,106,107,108,109,110,111,112,113,114,203,204,205,
                    206,207,208,209,126,115,116,117,118,119,120,121,122,210,
                    211,212,213,214,215,216,217,218,219,220,221,222,223,224,
                    225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72,
                    73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81,
                    82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89,
                    90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57,
                    250,251,252,253,254,255)
            import string
            c.EBCDIC_TO_ASCII_MAP = string.maketrans( \
            ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
        return s.translate(c.EBCDIC_TO_ASCII_MAP) 
开发者ID:Autodesk,项目名称:arnold-usd,代码行数:26,代码来源:__init__.py

示例4: text_to_word_sequence

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def text_to_word_sequence(text,
                          filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
                          lower=True,
                          split=' '):
  """Converts a text to a sequence of word indices.

  Arguments:
      text: Input text (string).
      filters: Sequence of characters to filter out.
      lower: Whether to convert the input to lowercase.
      split: Sentence split marker (string).

  Returns:
      A list of integer word indices.
  """
  if lower:
    text = text.lower()
  text = text.translate(maketrans(filters, split * len(filters)))
  seq = text.split(split)
  return [i for i in seq if i] 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:22,代码来源:text.py

示例5: b64decode

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def b64decode(s, altchars=None):
    """Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s is
    incorrectly padded.  Characters that are neither in the normal base-64
    alphabet nor the alternative alphabet are discarded prior to the padding
    check.
    """
    if altchars is not None:
        s = s.translate(string.maketrans(altchars[:2], '+/'))
    try:
        return binascii.a2b_base64(s)
    except binascii.Error, msg:
        # Transform this exception for consistency
        raise TypeError(msg) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:base64.py

示例6: test_trivial

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace(os.sep, '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:26,代码来源:test_urllib2.py

示例7: normalize

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def normalize(str):
    """
        Normalizes the string making string all lower case and removes all punctuation.
        :param str: string to be normalized
        :return: normalized string, if str is None or empty it returns the original string
    """

    if str:
        if isinstance(str, unicode):
            not_letters_or_digits = u'!"#%\'()*+,-./:;<=>?@[\]^_`{|}~'
            translate_to = u''
            translate_table = dict((ord(char), translate_to) for char in not_letters_or_digits)
            return str.translate(translate_table)
        else:
            return str.lower().translate(string.maketrans("",""), string.punctuation)
    else:
        return str 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:19,代码来源:strings_utils.py

示例8: test_trivial

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def test_trivial(self):
        # A couple trivial tests

        self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')

        # XXX Name hacking to get this to work on Windows.
        fname = os.path.abspath(urllib2.__file__).replace('\\', '/')

        # And more hacking to get it to work on MacOS. This assumes
        # urllib.pathname2url works, unfortunately...
        if os.name == 'riscos':
            import string
            fname = os.expand(fname)
            fname = fname.translate(string.maketrans("/.", "./"))

        if os.name == 'nt':
            file_url = "file:///%s" % fname
        else:
            file_url = "file://%s" % fname

        f = urllib2.urlopen(file_url)

        buf = f.read()
        f.close() 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:26,代码来源:test_urllib2.py

示例9: do_simple_substitution

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
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 
开发者ID:nccgroup,项目名称:featherduster,代码行数:21,代码来源:helpers.py

示例10: morse_decode

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
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()]) 
开发者ID:nccgroup,项目名称:featherduster,代码行数:18,代码来源:classical.py

示例11: is_text

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def is_text(s, threshold=0.3):
    """
    Determine whether a certain string is text or arbitrary bytes.
    This is derived from Python Cookbook
    :param s: string, input string
    :param threshold: float, threshold for the max proportion in a string which can be null translates
    :return: 
    """
    import string
    text_characters = "".join(map(chr, range(32, 127)))+"\n\r\t\b"
    _null_trans = string.maketrans("", "")
    if "\0" in s:
        return False
    if not s:
        return True
    t = s.translate(_null_trans, text_characters)
    return len(t)/len(s) <= threshold 
开发者ID:liyao001,项目名称:BioQueue,代码行数:19,代码来源:baseDriver.py

示例12: is_text

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def is_text(filename):
    s=open(filename).read(512)
    text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
    _null_trans = string.maketrans("", "")
    if not s:
        # Empty files are considered text
        return True
    if "\0" in s:
        # Files with null bytes are likely binary
        return False
    # Get the non-text characters (maps a character to itself then
    # use the 'remove' option to get rid of the text characters.)
    t = s.translate(_null_trans, text_characters)
    # If more than 30% non-text characters, then
    # this is considered a binary file
    if float(len(t))/float(len(s)) > 0.30:
        return False
    return True 
开发者ID:vicariousinc,项目名称:pixelworld,代码行数:20,代码来源:misc.py

示例13: __init__

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def __init__(self, widths, heights, is_training):
    """Constructs a VGSLSpecs.

    Args:
      widths:  Tensor of size batch_size of the widths of the inputs.
      heights: Tensor of size batch_size of the heights of the inputs.
      is_training: True if the graph should be build for training.
    """
    # The string that was used to build this model.
    self.model_str = None
    # True if we are training
    self.is_training = is_training
    # Tensor for the size of the images, of size batch_size.
    self.widths = widths
    self.heights = heights
    # Overall reduction factors of this model so far for each dimension.
    # TODO(rays) consider building a graph from widths and heights instead of
    # computing a scale factor.
    self.reduction_factors = [1.0, 1.0, 1.0, 1.0]
    # List of Op parsers.
    # TODO(rays) add more Op types as needed.
    self.valid_ops = [self.AddSeries, self.AddParallel, self.AddConvLayer,
                      self.AddMaxPool, self.AddDropout, self.AddReShape,
                      self.AddFCLayer, self.AddLSTMLayer]
    # Translation table to convert unacceptable characters that may occur
    # in op strings that cannot be used as names.
    self.transtab = maketrans('(,)', '___') 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:29,代码来源:vgslspecs.py

示例14: b64sub

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
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) 
开发者ID:HarmJ0y,项目名称:Arya,代码行数:9,代码来源:arya.py

示例15: maketrans

# 需要导入模块: import string [as 别名]
# 或者: from string import maketrans [as 别名]
def maketrans(cls, frm, to):
        """
        B.maketrans(frm, to) -> translation table

        Return a translation table (a bytes object of length 256) suitable
        for use in the bytes or bytearray translate method where each byte
        in frm is mapped to the byte at the same position in to.
        The bytes objects frm and to must be of the same length.
        """
        return newbytes(string.maketrans(frm, to)) 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:12,代码来源:newbytes.py


注:本文中的string.maketrans方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。