python str has no attribute_Python AttributeError: module 'string' has no attribute 'maketrans'

问题

I am receiving the below error when trying to run a command in Python 3.5.2 shell:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit

(Intel)] on win32 Type "copyright", "credits" or "license()" for more information.

>>> folder = 'C:/users/kdotz/desktop'

>>> f = open(folder + '/genesis.txt', 'r')

>>> import operator, time, string

>>> start=time.time()

>>> genesis = {}

>>> for line in f:

line=line.split()

for word in line:

word = word.lower()

new_word=word.translate(string.maketrans("",""), string.punctutation)

if new_word in genesis:

genesis[new_word]+=1

else:

genesis[new_word]=1

Traceback (most recent call last):

File "", line 5, in

new_word=word.translate(string.maketrans("",""), string.punctutation)

AttributeError: module 'string' has no attribute 'maketrans'

What am I doing incorrectly? I import string at the top of the code. Thanks in advance for the help!

回答1:

maketrans is deprecated in favor of new static methods

The string.maketrans() function is deprecated and is replaced by new static methods, bytes.maketrans() and bytearray.maketrans(). This change solves the confusion around which types were supported by the string module. Now, str, bytes, and bytearray each have their own maketrans and translate methods with intermediate translation tables of the appropriate type.

You can use dir() to verify that whenever you have this kind of issue:

>>> import string

>>>

>>> dir(string)

['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

>>>

As you can see, there is no maketrans in the resulted list above.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值