Python string.maketrans() Examples

The following are 30 code examples for showing how to use string.maketrans(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: bugatsinho.github.io   Author: bugatsinho   File: sport365.py    License: 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
Project: CapTipper   Author: omriher   File: CTMagic.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 
Example 3
Project: arnold-usd   Author: Autodesk   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 4
Project: lambda-packs   Author: ryfeus   File: text.py    License: MIT License 6 votes vote down vote up
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] 
Example 5
Project: ironpython2   Author: IronLanguages   File: base64.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_urllib2.py    License: Apache License 2.0 6 votes vote down vote up
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() 
Example 7
Project: locality-sensitive-hashing   Author: singhj   File: strings_utils.py    License: MIT License 6 votes vote down vote up
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 
Example 8
Project: faces   Author: skarlekar   File: _bsoup.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 9
Project: nightmare   Author: joxeankoret   File: BeautifulSoup.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 10
Project: xbmc-betaseries   Author: skylex   File: BeautifulSoup.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 11
Project: xbmc-betaseries   Author: skylex   File: BeautifulSoup.py    License: GNU General Public License v2.0 6 votes vote down vote up
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) 
Example 12
Project: BinderFilter   Author: dxwu   File: test_urllib2.py    License: MIT License 6 votes vote down vote up
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() 
Example 13
Project: featherduster   Author: nccgroup   File: helpers.py    License: 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 14
Project: featherduster   Author: nccgroup   File: classical.py    License: 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 15
Project: BioQueue   Author: liyao001   File: baseDriver.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 16
Project: pixelworld   Author: vicariousinc   File: misc.py    License: MIT License 6 votes vote down vote up
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 
Example 17
Project: DOTA_models   Author: ringringyi   File: vgslspecs.py    License: Apache License 2.0 5 votes vote down vote up
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('(,)', '___') 
Example 18
Project: Arya   Author: HarmJ0y   File: arya.py    License: 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) 
Example 19
Project: verge3d-blender-addon   Author: Soft8Soft   File: newbytes.py    License: GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example 20
Project: misp42splunk   Author: remg427   File: newbytes.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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)) 
Example 21
Project: misp42splunk   Author: remg427   File: newbytes.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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)) 
Example 22
Project: recruit   Author: Frank-qlu   File: test_strings.py    License: Apache License 2.0 5 votes vote down vote up
def test_translate(self):

        def _check(result, expected):
            if isinstance(result, Series):
                tm.assert_series_equal(result, expected)
            else:
                tm.assert_index_equal(result, expected)

        for klass in [Series, Index]:
            s = klass(['abcdefg', 'abcc', 'cdddfg', 'cdefggg'])
            if not compat.PY3:
                import string
                table = string.maketrans('abc', 'cde')
            else:
                table = str.maketrans('abc', 'cde')
            result = s.str.translate(table)
            expected = klass(['cdedefg', 'cdee', 'edddfg', 'edefggg'])
            _check(result, expected)

            # use of deletechars is python 2 only
            if not compat.PY3:
                result = s.str.translate(table, deletechars='fg')
                expected = klass(['cdede', 'cdee', 'eddd', 'ede'])
                _check(result, expected)

                result = s.str.translate(None, deletechars='fg')
                expected = klass(['abcde', 'abcc', 'cddd', 'cde'])
                _check(result, expected)
            else:
                msg = "deletechars is not a valid argument"
                with pytest.raises(ValueError, match=msg):
                    result = s.str.translate(table, deletechars='fg')

        # Series with non-string values
        s = Series(['a', 'b', 'c', 1.2])
        expected = Series(['c', 'd', 'e', np.nan])
        result = s.str.translate(table)
        tm.assert_series_equal(result, expected) 
Example 23
Project: neverendshadowsocks   Author: ntfreedom   File: table.py    License: Apache License 2.0 5 votes vote down vote up
def get_table(key):
    m = hashlib.md5()
    m.update(key)
    s = m.digest()
    a, b = struct.unpack('<QQ', s)
    table = maketrans(b'', b'')
    table = [table[i: i + 1] for i in range(len(table))]
    for i in range(1, 1024):
        table.sort(key=lambda x: int(a % (ord(x) + i)))
    return table 
Example 24
Project: neverendshadowsocks   Author: ntfreedom   File: table.py    License: Apache License 2.0 5 votes vote down vote up
def init_table(key):
    if key not in cached_tables:
        encrypt_table = b''.join(get_table(key))
        decrypt_table = maketrans(encrypt_table, maketrans(b'', b''))
        cached_tables[key] = [encrypt_table, decrypt_table]
    return cached_tables[key] 
Example 25
Project: CVE-2017-7494   Author: joxeankoret   File: dot11.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __set_field_values( self, field, values ):
        if not hasattr(values,'__iter__'):
            raise Exception("arg 'values' is not iterable")
        
        # It's for to known the qty of argument of a structure
        num_fields=len(field.STRUCTURE.translate(string.maketrans("",""), '=@!<>'))

        if len(values)!=num_fields:
            raise Exception("Field %s has exactly %d items"%(str(field),struct.calcsize(field.STRUCTURE)))
        
        is_present=self.get_present_bit(field)
        if is_present is False:
            self.__set_present_bit(field)
        
        byte_pos=self.__get_field_position(field)
        header=self.get_header_as_string()
        total_length=struct.calcsize(field.STRUCTURE)
        v=header[ byte_pos:byte_pos+total_length ]
        
        new_str = struct.pack(field.STRUCTURE, *values)

        if is_present is True:
            header=header[:byte_pos]+new_str+header[byte_pos+total_length:]
        else:
            header=header[:byte_pos]+new_str+header[byte_pos:]
        self.load_header(header) 
Example 26
Project: CAPTCHA-breaking   Author: lllcho   File: text.py    License: MIT License 5 votes vote down vote up
def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "):
    '''prune: sequence of characters to filter out
    '''
    if lower:
        text = text.lower()
    text = text.translate(maketrans(filters, split*len(filters)))
    seq = text.split(split)
    return [_f for _f in seq if _f] 
Example 27
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_string_attribute(self):
        node = astroid.extract_node(
            """
        import string
        string.maketrans #@
        """
        )
        message = testutils.Message("deprecated-string-function", node=node)
        with self.assertAddsMessages(message):
            self.checker.visit_attribute(node) 
Example 28
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_string_attribute(self):
        node = astroid.extract_node(
            """
        import string
        string.maketrans #@
        """
        )
        message = testutils.Message("deprecated-string-function", node=node)
        with self.assertAddsMessages(message):
            self.checker.visit_attribute(node) 
Example 29
Project: meddle   Author: glmcdona   File: urllib.py    License: MIT License 5 votes vote down vote up
def test(args=[]):
    if not args:
        args = [
            '/etc/passwd',
            'file:/etc/passwd',
            'file://localhost/etc/passwd',
            'ftp://ftp.gnu.org/pub/README',
            'http://www.python.org/index.html',
            ]
        if hasattr(URLopener, "open_https"):
            args.append('https://synergy.as.cmu.edu/~geek/')
    try:
        for url in args:
            print '-'*10, url, '-'*10
            fn, h = urlretrieve(url, None, reporthook)
            print fn
            if h:
                print '======'
                for k in h.keys(): print k + ':', h[k]
                print '======'
            with open(fn, 'rb') as fp:
                data = fp.read()
            if '\r' in data:
                table = string.maketrans("", "")
                data = data.translate(table, "\r")
            print data
            fn, h = None, None
        print '-'*40
    finally:
        urlcleanup() 
Example 30
Project: meddle   Author: glmcdona   File: build_ext.py    License: MIT License 5 votes vote down vote up
def get_ext_fullpath(self, ext_name):
        """Returns the path of the filename for a given extension.

        The file is located in `build_lib` or directly in the package
        (inplace option).
        """
        # makes sure the extension name is only using dots
        all_dots = string.maketrans('/'+os.sep, '..')
        ext_name = ext_name.translate(all_dots)

        fullname = self.get_ext_fullname(ext_name)
        modpath = fullname.split('.')
        filename = self.get_ext_filename(ext_name)
        filename = os.path.split(filename)[-1]

        if not self.inplace:
            # no further work needed
            # returning :
            #   build_dir/package/path/filename
            filename = os.path.join(*modpath[:-1]+[filename])
            return os.path.join(self.build_lib, filename)

        # the inplace option requires to find the package directory
        # using the build_py command for that
        package = '.'.join(modpath[0:-1])
        build_py = self.get_finalized_command('build_py')
        package_dir = os.path.abspath(build_py.get_package_dir(package))

        # returning
        #   package_dir/filename
        return os.path.join(package_dir, filename)