如何解决'str'在python中没有属性'maketrans'错误?

时间:2013-09-28 07:08:38

标签: python

运行python proxy.py

时出错
$ python proxy.py 
INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!
Traceback (most recent call last):
  File "proxy.py", line 2210, in <module>
    main()
  File "proxy.py", line 2180, in main
    pre_start()
  File "proxy.py", line 2157, in pre_start
    common.set_appids(get_appids())
  File "proxy.py", line 94, in get_appids
    fly = bytes.maketrans(
AttributeError: type object 'str' has no attribute 'maketrans'

https://code.google.com/p/smartladder/中的proxy.py文件,

def get_appids():
    fly = bytes.maketrans(
        b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
    )
    f = urllib.request.urlopen(url="http://lovejiani.com/v").read().translate(fly)
    d = base64.b64decode(f)
    e = str(d, encoding='ascii').split('\r\n')
    random.shuffle(e)
    return  e

1 个答案:

答案 0 :(得分:13)

您正在运行使用Python 2为Python 3编写的代码。这不起作用。

maketransbytes内置类型的类方法,但仅在Python 3中

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

在Python 2中,bytesstr的别名,但该类型具有该方法:

# 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'

使用Python 3运行代码,或者将此项目中的所有代码翻译为Python 2;后者需要深入了解Python 2和3的不同之处,并且可能是一项重大任务。

只是图示的函数,翻译成Python 2,将是:

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