Python AttributeError:模块“字符串"没有属性"maketrans" [英] Python AttributeError: module 'string' has no attribute 'maketrans'

查看:409
本文介绍了Python AttributeError:模块“字符串"没有属性"maketrans"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Python 3.5.2 shell中运行命令时收到以下错误:

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 "<pyshell#15>", line 5, in <module>
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!

推荐答案

maketrans已被弃用,而采用了新的静态方法

maketrans is deprecated in favor of new static methods

不推荐使用string.maketrans()函数,并由新的静态方法bytes.maketrans()和bytearray.maketrans()代替.此更改解决了字符串模块支持哪些类型的混淆.现在,str,bytes和bytearray都有自己的maketrans和translate方法,并带有适当类型的中间转换表.

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.

只要出现这种问题,就可以使用dir()进行验证:

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

如您所见,上面的结果列表中没有maketrans.

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

这篇关于Python AttributeError:模块“字符串"没有属性"maketrans"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆