How to resolve 'str' has no attribute 'maketrans' error in python?

后端 未结 1 1783
感动是毒
感动是毒 2021-01-11 10:39

I got an error while run python proxy.py

$ python proxy.py 
INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!
Traceback (most rece         


        
相关标签:
1条回答
  • 2021-01-11 11:01

    You are running code written for Python 3, with Python 2. This won't work.

    maketrans is a classmethod on the bytes built-in type, but only in Python 3.

    # Python 3
    >>> bytes
    <class 'bytes'>
    >>> bytes.maketrans
    <built-in method maketrans of type object at 0x10aa6fe70>
    

    In Python 2, bytes is an alias for str, but that type does not have that method:

    # Python 2.7
    >>> bytes
    <type 'str'>
    >>> bytes.maketrans
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: type object 'str' has no attribute 'maketrans'
    

    Run your code with Python 3 instead, or translate all code in this project to Python 2; the latter requires in-depth knowledge of how Python 2 and 3 differ and is likely a major undertaking.

    Just the illustrated function, translated to Python 2, would be:

    import string
    import urllib2
    import base64
    import random
    
    def get_appids():
        fly = string.maketrans(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
            "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
        )
        f = urllib2.urlopen("http://lovejiani.com/v").read().translate(fly)
        d = base64.b64decode(f)
        e = unicode(d, encoding='ascii').split(u'\r\n')
        random.shuffle(e)
        return e
    
    0 讨论(0)
提交回复
热议问题