如何解决'str'在Python中没有属性'maketrans'错误?
问题内容:
运行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
问题答案:
您正在使用Python 2运行为Python 3编写的代码。这将无法工作。
maketrans
是bytes
内置类型的类方法,但 仅在Python 3中 。
# Python 3
>>> bytes
<class 'bytes'>
>>> bytes.maketrans
<built-in method maketrans of type object at 0x10aa6fe70>
在Python 2,bytes
是一个别名str
,但该类型并 没有 有方法:
# 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